本文整理汇总了Python中nuorisovaalitadmin.models.DBSession.query方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.query方法的具体用法?Python DBSession.query怎么用?Python DBSession.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nuorisovaalitadmin.models.DBSession
的用法示例。
在下文中一共展示了DBSession.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_results_index__with_votes
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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)
示例2: test_password_change_form
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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'})
示例3: test_login__form_submission__success_with_full_identity
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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.'])
示例4: test_send_confirmation_message
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_send_confirmation_message(self, send_mail):
from email.message import Message
from nuorisovaalitadmin.models import PasswordReset
from nuorisovaalitadmin.models import School
from nuorisovaalitadmin.models import User
self.config.add_settings(DUMMY_SETTINGS)
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()
userid = user.id
view = self._makeView(post={'username': u'john.doe'})
response = view.send_confirmation_message()
self.assertEquals(1, session.query(PasswordReset).filter_by(user_id=userid).count())
self.assertEquals(response.location, 'http://example.com')
self.assertEquals(view.request.session.pop_flash(),
[u'Ohjeet salasanan vaihtamiseen on lähetetty sähköpostissa.'])
self.assertEquals(send_mail.call_args[0][0], u'[email protected]')
self.assertEquals(send_mail.call_args[0][1], [u'[email protected]'])
self.failUnless(isinstance(send_mail.call_args[0][2], Message))
示例5: test_login__form_submission__invalid_password
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_login__form_submission__invalid_password(self):
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))
session.flush()
self.assertEquals(
session.query(User).filter_by(username=u'john.doe').first().email,
u'[email protected]')
request = testing.DummyRequest()
token = request.session.new_csrf_token()
request.POST = {
'form.submitted': u'1',
'username': u'john.doe',
'password': u'thisiswrong',
'csrf_token': token,
}
options = login(request)
self.assertEquals(options, {
'title': u'Kirjaudu sisään',
'action_url': 'http://example.com/login',
'username': u'john.doe',
'reset_url': 'http://example.com/reset-password',
'csrf_token': token})
示例6: result_submission_stats
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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,
}
示例7: test_results_total_xls__no_votes
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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)
示例8: test_voter_submission_stats__submissions
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_voter_submission_stats__submissions(self):
from nuorisovaalit.models import School
from nuorisovaalitadmin.models import CSVSubmission
from nuorisovaalitadmin.models import User
from nuorisovaalitadmin.views.allianssi import voter_submission_stats
session = DBSession()
populate_testing_db()
eschools = session.query(School)\
.join(User)\
.filter(User.eparticipation == True)\
.all()
self.assertTrue(len(eschools) > 0)
school = eschools[0]
# Check that there is no submission to begin with.
self.assertEquals(0, session.query(CSVSubmission).count())
# Add a submission for the school.
session.add(CSVSubmission({}, school, CSVSubmission.VOTER))
session.flush()
school_count = len(eschools)
school_names_not_submitted = [s.name for s in eschools if s.name != school.name]
options = voter_submission_stats(DummyRequest())
options_not_submitted = [s.name for s in options['schools_not_submitted']]
self.assertEquals(school_count - 1, len(options_not_submitted))
self.assertEquals(school_names_not_submitted, options_not_submitted)
示例9: test_prune_expired__empty
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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_prune_expired
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_prune_expired(self):
from nuorisovaalitadmin.models import PasswordReset
view = self._makeView()
session = DBSession()
session.add(PasswordReset(1, datetime.now() - timedelta(days=30)))
session.add(PasswordReset(2, datetime.now() + timedelta(days=30)))
self.assertEquals(2, session.query(PasswordReset).count())
view.prune_expired()
self.assertEquals(1, session.query(PasswordReset).count())
self.assertEquals(2, session.query(PasswordReset).first().user_id)
示例11: test_password_change_form__invalid_user
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_password_change_form__invalid_user(self):
from nuorisovaalitadmin.models import PasswordReset
from nuorisovaalitadmin.models import User
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())
self.assertEquals(None, session.query(User).get(1))
view.request.matchdict['token'] = reset.token
self.assertRaises(NotFound, view.password_change_form)
示例12: login
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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(),
}
示例13: populate_voting_results
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def populate_voting_results():
"""Reads the paper ballot submissions and populates the database with new
:py:class:`nuorisovaalit.models.Vote` records based on them.
"""
session = DBSession()
records = failures = 0
for submission in session.query(CSVSubmission).filter_by(kind=CSVSubmission.RESULT).all():
print 'Processing', submission.school.name.encode('utf-8')
# Find all the candidates that belong to the district associated with the school.
candidates = dict((c.number, c) for c in submission.school.district.candidates)
for record in submission.csv:
number = int(record['number'])
votes = int(record['votes'])
if number in candidates:
session.add(Vote(candidates[number], submission.school, Vote.PAPER, votes))
records += 1
else:
failures += 1
print >> sys.stderr, 'Unknown candidate number {0} in district {1}'.format(number, submission.school.district.name.encode('utf-8'))
if failures == 0:
session.flush()
transaction.commit()
print 'Populated {0} voting records.'.format(records)
else:
print >> sys.stderr, 'Aborting due to {0} failure(s).'.format(failures)
transaction.abort()
示例14: voter_submission_counts
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
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)
示例15: test_create_message
# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import query [as 别名]
def test_create_message(self):
from nuorisovaalitadmin.models import PasswordReset
from nuorisovaalitadmin.models import School
from nuorisovaalitadmin.models import User
session = DBSession()
populate_testing_db()
self.config.add_settings(DUMMY_SETTINGS)
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(2010, 11, 15, 17, 20), u'uniquetoken')
view = self._makeView()
message = view.create_message(user, reset)
self.assertEquals(unicode(message['Subject']), u'john.doe')
self.assertEquals(unicode(message['From']), u'[email protected]')
self.assertEquals(unicode(message['To']), u'john.doe <[email protected]>')
message_str = message.as_string()
# Check that the relevant bits of information are included in the message
self.failUnless('john.doe' in message_str)
self.failUnless('15.11.2010 17:20' in message_str)
self.failUnless('http://example.com/reset-password/uniquetoken' in message_str)