当前位置: 首页>>代码示例>>Python>>正文


Python DBSession.flush方法代码示例

本文整理汇总了Python中nuorisovaalitadmin.models.DBSession.flush方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.flush方法的具体用法?Python DBSession.flush怎么用?Python DBSession.flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nuorisovaalitadmin.models.DBSession的用法示例。


在下文中一共展示了DBSession.flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_password_change_form

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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'})
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:30,代码来源:test_login.py

示例2: test_login__form_submission__invalid_password

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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})
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:33,代码来源:test_login.py

示例3: test_send_confirmation_message

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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))
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:29,代码来源:test_login.py

示例4: populate_voting_results

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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()
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:30,代码来源:populate.py

示例5: test_create_message

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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)
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:29,代码来源:test_login.py

示例6: test_voter_submission_stats__submissions

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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)
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:32,代码来源:test_allianssi.py

示例7: test_results_total_xls__no_votes

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [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)
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:36,代码来源:test_allianssi.py

示例8: populate_testing_db

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
def populate_testing_db():
    session = DBSession()
    populate_db()
    school = session.query(School).first()
    session.add(User(u'keijo',
                     u'passwd',
                     u'Keijo Käyttäjä',
                     '[email protected]',
                     True,
                     school))
    session.flush()
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:13,代码来源:__init__.py

示例9: test_groupfinder__with_groups

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
    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'])
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:16,代码来源:test_login.py

示例10: populate_db

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
def populate_db():
    from nuorisovaalit.models import District
    from nuorisovaalit.models import School
    from nuorisovaalitadmin.models import Group
    from nuorisovaalitadmin.models import User

    session = DBSession()
    district = District(u'Ylöjärven vaalipiiri', 1)
    session.add(district)
    session.flush()

    school = School(u'Äältö-yliopisto', district)
    session.add(school)
    session.flush()

    grp_admin = Group('admin', u'Admins')
    grp_school = Group('school', u'Schools')
    grp_allianssi = Group('allianssi', u'Allianssi')

    usr_admin = User('usr_admin', 'testi', u'Admin user', '[email protected]', True, school, grp_admin)
    usr_school = User('usr_school', 'testi', u'School user', '[email protected]', True, school, grp_school)
    usr_allianssi = User('usr_allianssi', 'testi', u'Allianssi user', '[email protected]', True, school, grp_allianssi)

    session.add(usr_admin)
    session.add(usr_school)
    session.add(usr_allianssi)
    session.flush()

    usr_admin.groups.append(grp_admin)
    usr_school.groups.append(grp_school)
    usr_allianssi.groups.append(grp_allianssi)
    session.flush()
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:34,代码来源:test_functional.py

示例11: populate_demo

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
def populate_demo():
    engine = engine_from_config(get_config(), 'sqlalchemy.')
    initialize_sql(engine)
    session = DBSession()
    engine.echo = False

    school1 = session.query(School).get(1)
    school2 = session.query(School).get(2)
    school3 = session.query(School).get(3)

    grp_admin = Group('admin', u'Administrators')
    grp_allianssi = Group('xxxx', u'xxxx')
    grp_school = Group('school', u'Schools')
    grp_school_limited = Group('school_limited', u'Schools (results only)')

    session.add(grp_admin)
    session.add(grp_allianssi)
    session.add(grp_school)
    session.add(grp_school_limited)

    admin = User('admin', 'testi', u'Admin user', '[email protected]', True, school1)
    allianssi = User('xxxx', 'testi', u'xxxx', '[email protected]', True, school1)

    school_user1 = User('school1', 'testi', u'School user', '[email protected]', True, school1)
    school_user2 = User('school2', 'testi', u'School user', '[email protected]', True, school2)
    school_user3 = User('school3', 'testi', u'School user', '[email protected]', True, school3)

    admin.groups.append(grp_admin)
    allianssi.groups.append(grp_allianssi)
    school_user1.groups.append(grp_school)
    school_user2.groups.append(grp_school)
    school_user3.groups.append(grp_school_limited)

    session.add(admin)
    session.add(allianssi)
    session.add(school_user1)
    session.add(school_user2)
    session.add(school_user3)

    session.flush()
    transaction.commit()
    print("Generated demo accounts.")
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:44,代码来源:populate.py

示例12: test_change_password

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
    def test_change_password(self, remember):
        from nuorisovaalitadmin.models import PasswordReset
        from nuorisovaalitadmin.models import School
        from nuorisovaalitadmin.models import User

        session = DBSession()
        populate_testing_db()

        school = session.query(School).first()
        self.assertTrue(school is not None)

        remember.return_value = [('X-Login', 'john.doe')]
        user = User(u'john.doe', u'secret', u'Jöhn Döe', u'[email protected]com', school_or_id=school)
        session.add(user)
        session.flush()

        reset = PasswordReset(user.id, datetime.now() + timedelta(days=7), u'uniquetoken')
        session.add(reset)
        session.flush()

        self.assertEquals(1, session.query(PasswordReset)\
            .filter(PasswordReset.user_id == user.id)\
            .filter(PasswordReset.token == u'uniquetoken')\
            .filter(PasswordReset.expires >= datetime.now())\
            .count())

        view = self._makeView(post={
            'token': 'uniquetoken',
            'password': 'abc123',
            'confirm_password': 'abc123'})
        response = view.change_password()
        self.assertEquals(dict(response.headers), {
            'Content-Length': '0',
            'X-Login': 'john.doe',
            'Content-Type': 'text/html; charset=UTF-8',
            'Location': 'http://example.com'})
        # Check that the password was changed
        self.failUnless(session.query(User).filter_by(id=user.id).first().check_password('abc123'))
        # Check that the reset request was deleted
        self.assertEquals(0, session.query(PasswordReset).count())
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:42,代码来源:test_login.py

示例13: test_voter_submission_stats__submission_with_wrong_kind

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
    def test_voter_submission_stats__submission_with_wrong_kind(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]

        # Add a submission for the school.
        session.add(CSVSubmission({}, school, CSVSubmission.RESULT))
        session.flush()

        options = voter_submission_stats(DummyRequest())
        self.assertEquals(len(eschools), len(list(options['schools_not_submitted'])))
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:24,代码来源:test_allianssi.py

示例14: test_result_submission_stats__with_submission

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]
    def test_result_submission_stats__with_submission(self):
        from nuorisovaalit.models import School
        from nuorisovaalitadmin.models import CSVSubmission
        from nuorisovaalitadmin.views.allianssi import result_submission_stats

        session = DBSession()
        populate_testing_db()
        school_count = session.query(School).count()

        school = session.query(School).first()
        self.assertTrue(school is not None)
        session.add(CSVSubmission({}, school, CSVSubmission.RESULT))
        session.flush()

        options = result_submission_stats(DummyRequest())
        self.assertEquals(u'Tuloslista-info', options['title'])
        self.assertEquals(school_count, options['school_count'])
        self.assertEquals(1, options['school_count_submitted'])
        self.assertEquals(school_count - 1, options['school_count_not_submitted'])
        self.assertEquals('{0:.2f}'.format(100 * 1 / float(school_count)),
                          options['submitted'])
        self.assertEquals('{0:.2f}'.format(100 * (school_count - 1) / float(school_count)),
                          options['not_submitted'])
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:25,代码来源:test_allianssi.py

示例15: run

# 需要导入模块: from nuorisovaalitadmin.models import DBSession [as 别名]
# 或者: from nuorisovaalitadmin.models.DBSession import flush [as 别名]

#.........这里部分代码省略.........

        # Query the currently existing usernames to avoid UNIQUE violations.
        # The usernames are stored as OpenID identifiers so we need to extract
        # the usernames from the URLs.
        self.usernames.update([
            urlparse(openid).netloc.rsplit('.', 2)[0]
            for result in session.query(Voter.openid).all()
            for openid in result])

        # Query the voter submission and associated schools.
        submissions = session.query(School, CSVSubmission)\
              .join(CSVSubmission)\
              .filter(CSVSubmission.kind == CSVSubmission.VOTER)\
              .filter(CSVSubmission.timestamp > startdate)\
              .order_by(School.name)

        fh_openid = filesafe.createFile(self.filename('voters-openid_accounts-{id}.txt'), 'w')
        fh_email = filesafe.createFile(self.filename('voters-email-{id}.txt'), 'w')
        fh_labyrintti = filesafe.createFile(self.filename('voters-labyrintti-{id}.csv'), 'w')
        fh_itella = filesafe.createFile(self.filename('voters-itella-{id}.xls'), 'w')

        # Excel worksheet for Itella
        wb_itella = xlwt.Workbook(encoding='utf-8')
        ws_itella = wb_itella.add_sheet('xxxx')
        text_formatting = xlwt.easyxf(num_format_str='@')
        for col, header in enumerate([u'Tunnus', u'Salasana', u'Nimi', u'Osoite', u'Postinumero', u'Postitoimipaikka', u'Todennäköinen kunta']):
            ws_itella.write(0, col, header, text_formatting)
        rows_itella = count(1)

        school_count = voter_count = address_parse_errors = 0

        self.header('Starting to process submissions')

        for school, submission in submissions.all():
            self.header('Processing school: {0}'.format(school.name.encode('utf-8')))
            for voter in submission.csv:
                username = self.genusername(voter['firstname'], voter['lastname'])
                password = self.genpasswd()

                # Create the voter instance.
                openid = u'http://{0}.did.fi'.format(username)
                dob = date(*reversed([int(v.strip()) for v in voter['dob'].split('.', 2)]))
                session.add(Voter(openid, voter['firstname'], voter['lastname'], dob, voter['gsm'], voter['email'], voter['address'], school))

                # Write the OpenID account information.
                fh_openid.write(u'{0}|{1}\n'.format(username, password).encode('utf-8'))

                has_gsm, has_email = bool(voter['gsm'].strip()), bool(voter['email'].strip())
                if has_gsm or has_email:
                    if has_gsm:
                        # Write the Labyrintti information only if a GSM number is available.
                        message = self.SMS_TMPL.format(username=username, password=password).encode('utf-8')
                        if len(message) > 160:
                            transaction.abort()
                            raise ValueError('SMS message too long: {0}'.format(message))

                        fh_labyrintti.write('"{0}","{1}"\n'.format(
                            u''.join(voter['gsm'].split()).encode('utf-8'),
                            message))

                    if has_email:
                        # Write the email information for everybody with an address.
                        fh_email.write(u'{0}|{1}|{2}\n'.format(username, password, voter['email']).encode('utf-8'))

                else:
                    # Write the Itella information for those that only have an
                    # address. We rely on the validation to ensure that it is
                    # available.
                    match = RE_ADDRESS.match(voter['address'])
                    if match is not None:
                        street = match.group(1).strip().strip(u',').strip()
                        zipcode = match.group(2).strip().strip(u',').strip()
                        city = match.group(3).strip().strip(u',').strip()

                        row = rows_itella.next()
                        for col, item in enumerate([username, password, u'{0} {1}'.format(voter['firstname'].split()[0], voter['lastname']), street, zipcode, city]):
                            ws_itella.write(row, col, item, text_formatting)
                    else:
                        print 'Failed to parse address for {0}: {1}.'.format(username, voter['address'].encode('utf-8'))
                        address_parse_errors += 1
                        row = rows_itella.next()
                        for col, item in enumerate([username, password, u'{0} {1}'.format(voter['firstname'].split()[0], voter['lastname']), voter['address'], u'', u'', school.name]):
                            ws_itella.write(row, col, item, text_formatting)

                print username
                voter_count += 1
            school_count += 1

        wb_itella.save(fh_itella)
        fh_openid.close()
        fh_email.close()
        fh_labyrintti.close()
        fh_itella.close()

        session.flush()
        transaction.commit()

        self.header('Finished processing')
        print 'Processed', school_count, 'schools and', voter_count, 'voters.'
        print 'Address parsing failed for', address_parse_errors, 'users.'
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:104,代码来源:populate.py


注:本文中的nuorisovaalitadmin.models.DBSession.flush方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。