1 from django
.shortcuts
import get_object_or_404
2 from django
.http
import HttpResponseRedirect
3 from django
.db
import connection
4 from django
.template
.defaultfilters
import slugify
5 from django
.views
.decorators
.csrf
import csrf_exempt
7 from pgweb
.util
.contexts
import render_pgweb
8 from pgweb
.util
.misc
import get_client_ip
, varnish_purge
9 from pgweb
.util
.helpers
import HttpSimpleResponse
11 from .models
import Survey
, SurveyAnswer
, SurveyLock
14 def results(request
, surveyid
, junk
=None):
15 survey
= get_object_or_404(Survey
, pk
=surveyid
)
16 surveylist
= Survey
.objects
.all().order_by('-posted')
18 return render_pgweb(request
, 'community', 'survey/results.html', {
20 'surveylist': surveylist
,
24 # Served over insecure HTTP, the Varnish proxy strips cookies
26 def vote(request
, surveyid
):
27 surv
= get_object_or_404(Survey
, pk
=surveyid
)
29 # Check that we have a valid answer number
31 ansnum
= int(request
.POST
['answer'])
32 if ansnum
< 1 or ansnum
> 8:
33 return HttpSimpleResponse(request
, "Response error", "Invalid answer")
34 except Exception as e
:
35 # When no answer is given, redirect to results instead
36 return HttpResponseRedirect("/community/survey/%s-%s" % (surv
.id, slugify(surv
.question
)))
37 attrname
= "tot%s" % ansnum
39 # Do IP based locking...
40 addr
= get_client_ip(request
)
42 # Clean out any old junk
43 curs
= connection
.cursor()
44 curs
.execute("DELETE FROM survey_surveylock WHERE (\"time\" + '15 minutes') < now()")
46 # Check if we are locked
47 lock
= SurveyLock
.objects
.filter(ipaddr
=addr
)
49 return HttpSimpleResponse(request
, "Rate limited", "Too many requests from your IP in the past 15 minutes")
51 # Generate a new lock item, and store it
52 lock
= SurveyLock(ipaddr
=addr
)
55 answers
= SurveyAnswer
.objects
.get_or_create(survey
=surv
)[0]
56 setattr(answers
, attrname
, getattr(answers
, attrname
) + 1)
59 # Do explicit varnish purge, since it seems that the model doesn't
60 # do it properly. Possibly because of the cute stuff we do with
61 # getattr/setattr above.
62 varnish_purge("/community/survey/%s/" % surveyid
)
64 return HttpResponseRedirect("/community/survey/%s/" % surveyid
)