If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!
#!/usr/bin/env python
# coding: utf8
from __future__ import division  # for percentages
from gluon import *
 
"""
Usage:
 
model.py
----------
from polls import Polls
polls_db = DAL("sqlite://polls.db")
polls = Polls(polls_db)
polls.add_poll("color", "Which color?",
              ["red", "blue", "purple", "snuffy"]
              )
polls.define_tables()
 
controller.py
---------------
def index():
   poll = polls.get_poll('color')
   f = poll.form.process()
   if f.accepted or request.client in poll.voters:
       response.flash = "Thank you for voting!"
       results=poll.results
   return locals()
 
controller/view.html
--------------------
{{extend layout.html}}
{{if 'poll' in globals():}}
 {{=h3(T(poll.question))}}
 {{if 'results' in globals():}}
   {{=BEAUTIFY(results)}}
 {{else:}}
   {{=poll.form}}
   {{pass}}
 {{pass}}
"""
 
class Polls:
    def __init__(self, db):
        db.define_table("polls",
                        Field("name", unique=True),
                        Field("question"),
                        Field("choices", "list:string")
                        )
        self._db = db
 
    def define_tables(self):
        polls = self._db().select(self._db.polls.ALL)
        for p in polls:
            self._db.define_table(p.name,
                                  Field("user_ip", unique=True, default=current.request.client,
                                        readable=False, writable=False
                                        ),
                                  Field("answer", requires=IS_IN_SET(p.choices),
                                        widget=SQLFORM.widgets.radio.widget
                                        )
                                  )
 
    def add_poll(self, name, q, choices):
        self._db.polls.update_or_insert(name=name, question=q, choices=choices)
 
    def get_form(self, poll):
        return SQLFORM(self._db[poll])
 
    def get_results(self, poll):
        p_tbl = self._db.polls
        p_res_tbl = self._db[poll]
        this_poll = self._db(p_tbl.name == poll).select(p_tbl.ALL).first()
        choices = this_poll.choices
        total_votes = len(self._db().select(p_res_tbl.ALL))
 
        if total_votes:
            p_results = dict()
            for c in choices:
                this_count = self._db(p_res_tbl.answer == c).count()
                p_results[c] = '{}%'.format((this_count / total_votes) * 100)
            return p_results
        else:
            return False
 
    def get_poll(self, poll):
        return Poll(self, poll)
 
class Poll:
    def __init__(self, polls, name):
        db = polls._db
        self.name = name
        self.question = db(db.polls.name == name).select().first().question
        self.results = polls.get_results(name)
        self.voters = [r.user_ip for r in db().select(db[name].ALL)]
        self.form = polls.get_form(name)

Related slices

Comments (0)


Hosting graciously provided by:
Python Anywhere