Skip to content

Instantly share code, notes, and snippets.

@marodrig
Last active October 2, 2015 03:04
Show Gist options
  • Save marodrig/468b6bc98c74074c19d7 to your computer and use it in GitHub Desktop.
Save marodrig/468b6bc98c74074c19d7 to your computer and use it in GitHub Desktop.
view.py file for the admin/login of web application.
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from google.appengine.api.labs import taskqueue
from google.appengine.api import urlfetch
from django.template import Context, loader
import datetime,logging,urllib
import urllib2
#AppEngine imports.
from google.appengine.ext import db
from google.appengine.ext.db import NotSavedError, Error
from ragendja.dbutils import transaction
from polls.models import *
from polls import views
from polls import constants
def delete_poll_by_date(request):
"""
Deletes a series of polls by date
"""
logging.info("trying to delete polls")
try:
str_day = request.POST['day']
str_month = request.POST['month']
str_year = request.POST['year']
except KeyError, (strErr):
logging.info("Error: %s" % strErr )
date_end = datetime.date(int(str_year), int(str_month), int(str_day) )
query = Poll.all()
query.filter("audit_dt_created <", date_end)
poll_list = query.fetch(200)
int_count = 0
for p in poll_list:
p.delete_votes()
p.delete_answers()
p.delete()
pindex_list = PollIndex.all().ancestor(p).fetch(500)
db.delete(pindex_list)
int_count+=1
return HttpResponse("%d Polls deleted" % int_count )
def index_entities(request):
"""
Indexes entities use only when you would like to
delete the whole datastore
"""
logging.info("receiving request")
query = db.Query(PollIndex, keys_only=True)
try:
db.delete(query.fetch(5000))
except db.Error, (strError):
logging.error("Err: %s" % strError )
# we get all of them
query = db.Query(Poll, keys_only=True)
keys = query.fetch(2000)
for k in keys:
t = taskqueue.Task(
url='/polls/indexWorker/',
params={
'poll_id': k.id(),
}
)
t.add(queue_name="fast-index-queue")
logging.info("sent to task queue")
return HttpResponse("OK")
def display_categoryList(request):
"""
Only display a list of categories.
"""
cat_list = PollCategory.all()
c = Context({
'cat_list':cat_list,
})
t = loader.get_template('polls/CategoryList.html')
return HttpResponse(t.render(c))
def apply_changes_to_category(request):
try:
str_obj_key_id = request.POST['_id']
int_obj_key_id = int(str_obj_key_id)
obj_instance = PollCategory.get_by_id(int_obj_key_id)
except db.BadKeyError, (strerr):
logging.error("Error extracting from db: %s" % strerr )
return HttpResponseRedirect('/displayCategoryList/')
except KeyError, (strerr):
logging.error("ValueError: %s" % strerr)
# send to the html template
data = CatForm(data=request.POST, instance=obj_instance)
if data.is_valid():
logging.info("everything ok... saving category")
cat_obj = data.save(commit=False)
cat_obj.put()
else:
logging.info("uh oh, division by zero!")
t = loader.get_template('polls/catform.html')
c = Context({
'cat':data,
})
return HttpResponse(t.render(c))
return HttpResponseRedirect('/admin/displayCategoryList/')
def add_category(request):
"""
Add Poll category
"""
str_category = None
data = CatForm(data=request.POST)
if data.is_valid():
cat_obj = data.save(commit=False)
str_category = PollCategory.all().filter('name =',cat_obj.name).get()
if not str_category:
logging.info("Adding a new category.")
cat_obj.put()
else:
logging.info("category already exists")
errornum = 103
errormsg = 'Category is not available. Please choose another Category.'
c = Context({
'errornum':errornum,
'errormsg':errormsg,
})
t = loader.get_template('polls/errorpage.html')
return HttpResponse(t.render(c))
else:
logging.info("unexpeted error.")
t = loader.get_template('polls/catform.html')
c = Context({
'cat':data,
})
return HttpResponse(t.render(c))
#check if this is correct
cat_list = PollCategory.all()
c = Context({
'cat_list':cat_list
})
t = loader.get_template('polls/CategoryList.html')
return HttpResponse(t.render(c))
def edit_category(request, cat_id):
"""
"""
int_obj_key_id = int(cat_id)
obj_instance = None
try:
obj_instance = PollCategory.get( db.Key.from_path('PollCategory', int_obj_key_id) )
except KeyError, (strerr):
logging.error("Error extracting from db: %s" % strerr )
return HttpResponseRedirect('/CategoryList/')
# send to the html template
c = Context({
'cat':CatForm(instance=obj_instance),
})
t = loader.get_template('polls/catform.html')
return HttpResponse(t.render(c))
def display_cat_form(request):
"""
Register the poll category
"""
c = Context({
'cat':CatForm(),
})
t = loader.get_template('polls/catform.html')
return HttpResponse(t.render(c))
def rate_poll(request, poll_id):
"""
Display a given poll in a form in order to lower the ranking or
delete an offensive poll
"""
logging.info("receiving the poll id: %s" % poll_id )
int_poll_id = int(poll_id)
poll_obj = Poll.get_by_id(int_poll_id)
c = Context({
'poll':poll_obj,
'url': views.getUrl(),
})
t = loader.get_template('admin/ratePoll.html')
return HttpResponse(t.render(c))
def delete_poll(request, poll_id):
"""
deletes poll by id.
"""
logging.info("receiving the request")
int_obj_key_id = int(poll_id)
try:
obj_instance = Poll.get( db.Key.from_path('Poll', int_obj_key_id) )
except db.Error, (strerr):
logging.error("Error extracting from db: %s" % strerr )
return HttpResponse('Error: %s' % strerr )
if not obj_instance:
return HttpResponse('Error: poll no existe' )
email = obj_instance.author.email
try:
str_msg = request.POST['reason']
except KeyError, (strErr):
logging.info("E: %s" % strErr)
obj_instance.delete_votes()
obj_instance.delete_answers()
# important to delete the given indexes
pindex_list = PollIndex.all().ancestor(obj_instance).fetch(500)
db.delete(pindex_list)
obj_instance.delete()
#send email notification to Author.
t = taskqueue.Task(
url = '/polls/mailWorker/',
params = {
'msg': str_msg,
'to': email,
'from':constants.EMAIL_ACCOUNT,
'subject':"PieAll Admin Notification",
}
)
t.add(queue_name="mail-queue")
return HttpResponse('OK -- poll borrado')
def normalize_polls_answer_size(request):
"""
Function to be used only once, to normalize the polls answer size.
"""
logging.info("preparing to send all polls to answer size")
query = db.Query(Poll, keys_only=True)
poll_key_list = query.fetch(2000)
logging.info("poll list executed")
for key in poll_key_list:
t = taskqueue.Task(
url = '/admin/pollNormalizeWorker/',
params = {
'poll_key': key.id(),
}
)
t.add(queue_name="fast-index-queue")
return HttpResponse("ok - sent to normalize Worker")
def poll_normalize_worker(request):
"""
Function to be called from a task queue
"""
logging.debug("starting the worker")
poll_id = None
try:
poll_id = request.POST['poll_key']
except KeyError, (strErr):
logging.error("key not found in normalize worker: %s" % strErr)
if not poll_id:
return HttpResponse("Error")
# else we proceed
int_poll_id = int(poll_id)
poll_obj = Poll.get_by_id( int_poll_id )
total_answers = poll_obj.answers.count()
poll_obj.total_answers = total_answers
poll_obj.put()
return HttpResponse("OK")
def normalize_polls_answer_order(request):
"""
Function to be used only once, to normalize the polls answer size.
"""
logging.info("preparing to send all polls to answer size")
query = db.Query(Poll, keys_only=True)
poll_key_list = query.fetch(2000)
logging.info("poll list executed")
for key in poll_key_list:
t = taskqueue.Task(
url = '/admin/pollNormalizeAnswerWorker/',
params = {
'poll_key': key.id(),
}
)
t.add(queue_name="fast-index-queue")
return HttpResponse("ok - sent to normalize answer order Worker")
def poll_normalize_answer_worker(request):
"""
normalizes the answer
"""
logging.debug("receiving the answer")
poll_id = None
try:
poll_id = request.POST['poll_key']
except KeyError, (strErr):
logging.error("key not found in normalize worker: %s" % strErr)
if not poll_id:
return HttpResponse("Error")
# else we proceed
int_poll_id = int(poll_id)
poll_obj = Poll.get_by_id( int_poll_id )
int_pos = 0
for answer in poll_obj.answers:
# increment position
int_pos = int_pos + 1
answer.order = int_pos
answer.put()
return HttpResponse("OK")
def normalize_polls_blob_order(request):
"""
Function to be used only once, to normalize the polls answer size.
"""
logging.info("preparing to send all polls to answer size")
query = db.Query(Poll, keys_only=True)
query.filter("media =", None)
poll_key_list = query.fetch(2000)
logging.info("poll list executed")
for key in poll_key_list:
t = taskqueue.Task(
url = '/admin/normalizeImgWorker/',
params = {
'poll_key': key.id(),
}
)
t.add(queue_name="fast-index-queue")
return HttpResponse("ok - sent to normalize answer order Worker")
def normalize_img_worker(request):
"""
Process each vote, connecting to google to get the actual blob
"""
logging.debug("receiving the answer")
poll_id = None
try:
poll_id = request.POST['poll_key']
except KeyError, (strErr):
logging.error("key not found in normalize worker: %s" % strErr)
if not poll_id:
return HttpResponse("Error")
# else we proceed
int_poll_id = int(poll_id)
poll_obj = Poll.get_by_id( int_poll_id )
# now call the fetch
url = "http://" + poll_obj.get_chart_url()
#url = urllib.quote(url,safe="/")
logging.info("u: %s" % url )
try:
result = urlfetch.fetch(url)
#result = urllib2.urlopen(url)
except UnicodeEncodeError, (strErr):
logging.info("-------\nError en url: %s" % url)
if result.status_code == 200:
logging.info("ok - receiving")
poll_obj.media = db.Blob(result.content)
poll_obj.put()
else:
logging.error("error: en el url connect: %d" % result.status_code )
# now with the small embedded
return HttpResponse("OK")
def calculate_related_polls_worker(request):
"""
Calculates the related polls by IP
"""
logging.info("receiving related polls by worker")
poll_id = None
try:
poll_id = request.POST['poll_key']
except KeyError, (strError):
logging.info("Error: %s" % strError)
return HttpResponse("Error: %s" % strError)
# seguimos
int_poll_id = int(poll_id)
poll_obj = Poll.get_by_id( int_poll_id )
list_votes = poll_obj.votes
if not list_votes:
return HttpResponse("Error no list of votes")
list_ip = [vote.ip_address for vote in list_votes]
# now we get all the last 200 votes with these ips
for ip in list_ip:
query = db.Query(PollVotes, keys_only=True)
query.filter("ip_address =",ip )
query.order("-dt_created")
poll_votes = query.fetch(200)
#send it to process
return HttpResponse("OK")
def assign_related_poll_worker(request):
"""
Tasks to assign a poll to a specific poll
"""
logging.info("receiving the related poll worker assignment")
str_poll_id = None
str_related_poll_id = None
try:
str_poll_id = request.POST['poll_key']
str_related_poll_id = request.POST['rel_poll_key']
except KeyError, (strErr):
logging.error("No keys %s" % strErr)
return HttpResponse("Error")
int_poll_id = int(str_poll_id)
poll_obj = Poll.get_by_id( int_poll_id )
related_poll = Poll.get_by_id( str_related_poll_id )
# now we can make the association
def poll_state_worker(request):
"""
Determines if a polls has incorrectly recorded its votes
"""
str_poll_id = None
answer = None
try:
str_poll_id = request.POST['poll_id']
answer = request.POST['answer']
except KeyError, (strErr):
logging.info("Key error: %s" % strErr)
# obj instance
int_p_id = int(str_poll_id)
obj_instance = Poll.get_by_id( int_p_id )
query = db.Query(PollVotes, keys_only=True)
query.filter("poll =", obj_instance)
actual_votes = query.count(5000)
if actual_votes != obj_instance.total_votes:
obj_instance.state = u'invalid'
obj_instance.dt_last_update = datetime.datetime.now()
obj_instance.put()
return HttpResponse("OK")
def poll_answer_inc_worker(request):
"""
Increments each answer vote and each poll obj instance
"""
str_poll_id = None
answer = None
try:
str_poll_id = request.POST['poll_id']
answer = request.POST['answer']
except KeyError, (strErr):
logging.info("Key error: %s" % strErr)
# obj instance
int_p_id = int(str_poll_id)
obj_instance = Poll.get_by_id( int_p_id )
c = obj_instance.answers.filter("answer =", answer).get()
if c:
# first we increment the answer
c.total_votes += 1
c.put()
# and then we increment the total amount of votes for the poll
obj_instance.total_votes += 1
obj_instance.put()
logging.info("PollVotes incremented")
return HttpResponse("OK")
def display_user_list(request):
"""
Only display purposes of form for user information
"""
usr_list = PieAllUser.all()
c = Context({
'usr_list':usr_list,
})
t = loader.get_template('polls/UserList.html')
return HttpResponse(t.render(c))
def update_total_count_worker(request):
"""
Updates a vote
"""
poll_id = None
try:
poll_id = request.POST['poll_id']
except KeyError, (strError):
return HttpResponse(strError)
incrementPoll(poll_id)
return HttpResponse("OK")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment