本文整理汇总了Python中nuorisovaalitadmin.models.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: result_submission_stats
def result_submission_stats(request):
"""Renders statistics about the schools who have or have not submitted
paper ballot results.
"""
session = DBSession()
# Total number of schools participating in the voting.
school_count = session.query(School).count()
schools_not_submitted = session.query(School)\
.join(District)\
.filter(~School.csvsubmission.any(CSVSubmission.kind == CSVSubmission.RESULT))\
.order_by(District.name, School.name)\
.all()
school_count_not_submitted = len(schools_not_submitted)
school_count_submitted = school_count - school_count_not_submitted
submitted = '0.00'
not_submitted = '100.00'
if school_count > 0:
percentage = 100 * school_count_submitted / float(school_count)
submitted = '{0:.2f}'.format(percentage)
not_submitted = '{0:.2f}'.format(100 - percentage)
request.add_response_callback(disable_caching)
return {
'title': u'Tuloslista-info',
'school_count': school_count,
'school_count_submitted': school_count_submitted,
'school_count_not_submitted': school_count_not_submitted,
'submitted': submitted,
'not_submitted': not_submitted,
'schools_not_submitted': schools_not_submitted,
}
示例2: login
def login(request):
"""Renders a login form and logs in a user if given the correct
credentials.
"""
session = DBSession()
username = u''
log = logging.getLogger('nuorisovaalitadmin')
if 'form.submitted' in request.POST:
username = request.POST['username']
if request.session.get_csrf_token() != request.POST.get('csrf_token'):
log.warn('CSRF attempt at {0}.'.format(request.url))
raise Forbidden(u'CSRF attempt detected.')
else:
user = session.query(User).filter_by(username=username).first()
password = request.POST['password']
if user is not None and user.check_password(password):
headers = remember(request, user.username)
request.session.flash(u'Olet kirjautunut sisään.')
log.info('Successful login for "{0}".'.format(user.username))
return HTTPFound(location=request.application_url, headers=headers)
log.warn('Failed login attempt for {0}'.format(request.POST.get('username').encode('utf-8')))
request.session.flash(u'Kirjautuminen epäonnistui')
request.add_response_callback(disable_caching)
return {
'title': u'Kirjaudu sisään',
'action_url': route_url('login', request),
'username': username,
'reset_url': route_url('reset_password', request),
'csrf_token': request.session.get_csrf_token(),
}
示例3: results_template_xls
def results_template_xls(request):
"""Downloads an Excel sheet template for paper ballot results submission.
The Excel template contains the names and numbers of the candidates
associated with the school's voting district.
"""
rows = [
(u'Numero', u'Nimi', u'Äänimäärä'),
]
user = authenticated_user(request)
if user is None:
raise Forbidden
session = DBSession()
# Add all the candidates and their numbers into the CSV template.
candidates = session.query(Candidate)\
.filter(Candidate.district == user.school.district)\
.order_by(Candidate.number)
rows.extend((c.number, c.fullname(), u'') for c in candidates)
request.add_response_callback(disable_caching_explorer)
return xls_response(rows,
filename='nuorisovaalit2011-uurnatulokset.xls',
num_formats=('@', '@', '@'),
col_widths=(None, 8000, 3000))
示例4: test_password_change_form
def test_password_change_form(self):
from nuorisovaalitadmin.models import PasswordReset
from nuorisovaalitadmin.models import School
from nuorisovaalitadmin.models import User
view = self._makeView()
session = DBSession()
populate_testing_db()
school = session.query(School).first()
self.assertTrue(school is not None)
user = User(u'john.doe', u'secret', u'Jöhn Döe', u'[email protected]', school_or_id=school)
session.add(user)
session.flush()
reset = PasswordReset(user.id, datetime.now() + timedelta(days=7), u'uniquetoken')
session.add(reset)
self.assertEquals(1, session.query(PasswordReset).filter_by(token=reset.token).count())
self.assertEquals(u'john.doe', session.query(User).get(user.id).username)
view.request.matchdict['token'] = reset.token
self.assertEquals(view.password_change_form(), {
'username': u'john.doe',
'action_url': 'http://example.com/reset-password/process',
'token': u'uniquetoken',
'title': u'Vaihda salasana'})
示例5: test_login__form_submission__success_with_full_identity
def test_login__form_submission__success_with_full_identity(self, remember):
from nuorisovaalitadmin.models import School
from nuorisovaalitadmin.models import User
from nuorisovaalitadmin.views.login import login
session = DBSession()
populate_testing_db()
school = session.query(School).first()
self.assertTrue(school is not None)
session.add(User(u'john.doe', u'secret', u'Jöhn Döe', u'[email protected]', school_or_id=school))
self.assertEquals(
session.query(User).filter_by(username=u'john.doe').first().email,
u'[email protected]')
remember.return_value = [('X-Login', 'john.doe')]
request = testing.DummyRequest()
token = request.session.new_csrf_token()
request.POST = {
'form.submitted': u'1',
'username': u'john.doe',
'password': u'secret',
'csrf_token': token,
}
response = login(request)
self.assertEquals(dict(response.headers), {
'Content-Length': '0',
'Content-Type': 'text/html; charset=UTF-8',
'Location': 'http://example.com',
'X-Login': u'john.doe'})
self.assertEquals(request.session.pop_flash(), [u'Olet kirjautunut sisään.'])
示例6: voter_submission_counts
def voter_submission_counts():
"""Lists the schools that have submitted voters and the number of voters
for each school.
"""
engine = engine_from_config(get_config(), 'sqlalchemy.')
initialize_sql(engine)
session = DBSession()
query = session.query(School.name, CSVSubmission.csv)\
.join(CSVSubmission)\
.filter(CSVSubmission.kind == CSVSubmission.VOTER)\
.order_by(School.name)
stats = defaultdict(int)
for school, submission in query.all():
if school == u'Dummy school':
continue
print school, len(submission)
stats['total'] += len(submission)
for entry in submission:
if entry['gsm'].strip():
stats['gsm'] += 1
elif entry['email'].strip():
stats['email'] += 1
else:
stats['letter'] += 1
print
print 'Total voters: {total}'.format(**stats)
print 'SMS: {gsm}, Email: {email}, Letter: {letter}'.format(**stats)
示例7: validate
def validate(self, submission):
"""Validates the submitted data and returns a list of error messages
corresponding to validation failures.
Each error message is a dictionary containing the line number where
the error occurred and a message describing the error, e.g.::
{ 'lineno': 13, 'msg': u'Etunimi puuttuu.' }
:param submission: Iterable of dictionary containing the submission
data.
:type submission: iterable
:rtype: list
"""
errors = []
def missing(row, field):
return row.get(field) is None or len(row[field].strip()) == 0
def error(lineno, msg):
return dict(lineno=lineno, msg=msg)
def is_num(n):
return n is not None and n.strip().isdigit()
# Start line numbering from two since the header row was
# consumed while parsing.
for lineno, row in enumerate(submission, start=2):
if not any(v.strip() for v in row.values()):
# Skip empty rows.
continue
if missing(row, 'name'):
errors.append(error(lineno, u'Ehdokkaan nimi puuttuu.'))
if missing(row, 'votes'):
errors.append(error(lineno, u'Ehdokkaan äänimäärä puuttuu.'))
elif not is_num(row.get('votes')):
errors.append(error(lineno, u'Äänimäärä on väärää muotoa. Tarkista, että äänimäärä on positiivinen kokonaisluku.'))
if missing(row, 'number'):
errors.append(error(lineno, u'Ehdokasnumero puuttuu.'))
elif not is_num(row.get('number')):
errors.append(error(lineno, u'Ehdokasnumero on väärää muotoa. Tarkista, että ehdokasnumero on positiivinen kokonaisluku.'))
else:
# Check that there exists exactly one candidate with
# the given number who is in the same district as the
# user.
num = int(row.get('number').strip())
session = DBSession()
num_candidates = session.query(Candidate)\
.filter(Candidate.number == num)\
.filter(Candidate.district == self.user.school.district)\
.count()
if num_candidates != 1:
errors.append(error(lineno, u'Ehdokasnumero {0} ei vastaa yhtään vaalipiirin ehdokasta.'.format(num)))
return errors
示例8: test_groupfinder__no_groups
def test_groupfinder__no_groups(self):
from nuorisovaalitadmin.models import User
from nuorisovaalitadmin.views.login import groupfinder
session = DBSession()
session.add(User(u'dokai', u'secret', u'Kai', '[email protected]', school_or_id=1))
self.assertEquals([], groupfinder(u'dokai', testing.DummyRequest()))
示例9: test_prune_expired__empty
def test_prune_expired__empty(self):
from nuorisovaalitadmin.models import PasswordReset
view = self._makeView()
session = DBSession()
self.assertEquals(0, session.query(PasswordReset).count())
view.prune_expired()
self.assertEquals(0, session.query(PasswordReset).count())
示例10: test_index__authenticated
def test_index__authenticated(self):
from nuorisovaalitadmin.views.login import index
from nuorisovaalitadmin.models import User
session = DBSession()
populate_testing_db()
user = session.query(User).first()
self.config.testing_securitypolicy(userid=user.username)
self.assertEquals({}, index(DummyRequest()))
示例11: test_password_change_form__expired_token
def test_password_change_form__expired_token(self):
from nuorisovaalitadmin.models import PasswordReset
view = self._makeView()
reset = PasswordReset(1, datetime.now() - timedelta(days=7))
session = DBSession()
session.add(reset)
self.assertEquals(1, session.query(PasswordReset).filter_by(token=reset.token).count())
view.request.matchdict['token'] = reset.token
self.assertRaises(NotFound, view.password_change_form)
示例12: test_results_total_xls__no_votes
def test_results_total_xls__no_votes(self):
from nuorisovaalit.models import District
from nuorisovaalit.models import Vote
from nuorisovaalitadmin.views.allianssi import results_total_xls
session = DBSession()
populate_testing_db()
# Add a district with code 0.
self.assertEquals(0, session.query(District).filter_by(code=0).count())
session.add(District(u'Tyhjä piiri åäö', 0))
session.flush()
self.assertEquals(0, session.query(Vote).count())
response = results_total_xls(DummyRequest())
self.assertTrue(isinstance(response, Response))
self.assertEquals('application/vnd.ms-excel', response.headers['content-type'])
self.assertEquals('attachment; filename=nuorisovaalit2011-valtakunnalliset-tulokset.xls',
response.headers['content-disposition'])
wb = xlrd.open_workbook(file_contents=response.body)
district_names = [n[0] for n in session.query(District.name)]
self.assertTrue(len(district_names) > 1)
district_names.remove(u'Tyhjä piiri åäö')
# Cut long names.
district_names = sorted(d[:31] for d in district_names)
# Assert that there is a sheet in the Xls file for every
# district except the one with code 0.
sheet_names = sorted(wb.sheet_by_index(i).name for i in xrange(len(district_names)))
self.assertEquals(district_names, sheet_names)
示例13: test_results_index__with_votes
def test_results_index__with_votes(self):
from nuorisovaalit.models import Candidate
from nuorisovaalit.models import School
from nuorisovaalit.models import Vote
from nuorisovaalitadmin.views.allianssi import results_index
self.config.add_route('results_total_xls', '/results-total.xls')
session = DBSession()
populate_testing_db()
candidate = session.query(Candidate).first()
school = session.query(School)\
.filter_by(district_id=candidate.district_id)\
.first()
self.assertTrue(candidate is not None)
self.assertTrue(school is not None)
self.assertEquals(0, session.query(Vote).count())
session.add(Vote(candidate, school, Vote.PAPER, 15))
session.add(Vote(candidate, school, Vote.ELECTRONIC))
session.add(Vote(candidate, school, Vote.ELECTRONIC))
options = results_index(DummyRequest())
options.pop('voted')
options.pop('not_voted')
self.assertEquals({
'title': u'Tulokset',
'vote_count_total': 17,
'vote_count_electronic': 2,
'results_total_xls': 'http://example.com/results-total.xls',
}, options)
示例14: test_voter_submission_stats__no_schools
def test_voter_submission_stats__no_schools(self):
from nuorisovaalit.models import School
from nuorisovaalitadmin.views.allianssi import voter_submission_stats
session = DBSession()
# Check that there is no schools.
self.assertEquals(0, session.query(School).count())
options = voter_submission_stats(DummyRequest())
self.assertEquals(u'Äänestäjälista-info', options['title'])
self.assertEquals(0, options['school_count'])
self.assertEquals(0, options['school_count_submitted'])
self.assertEquals('0.00', options['submitted'])
self.assertEquals([], list(options['schools_not_submitted']))
示例15: test_groupfinder__with_groups
def test_groupfinder__with_groups(self):
from nuorisovaalitadmin.models import Group
from nuorisovaalitadmin.models import User
from nuorisovaalitadmin.views.login import groupfinder
session = DBSession()
user = User(u'dokai', u'secret', u'Kai', '[email protected]', school_or_id=1)
session.add(user)
session.flush()
user.groups.append(Group(u'coolios', u'Coolios'))
user.groups.append(Group(u'admins', u'Administrators'))
self.assertEquals(groupfinder(u'dokai', testing.DummyRequest()), [
'group:coolios', 'group:admins'])