Python transaction 模块,manager() 实例源码

我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用transaction.manager()

项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def main():
    session = make_session()
    with transaction.manager:
        old_friends = session.query(OldFriend).all()
        for old in old_friends:
            username = old.user
            friend_username = old.friend
            user_id = session.query(User.id).filter(User.username == username).first()[0]
            try:
            friend_id = session.query(User.id).filter(User.username == friend_username).first()[0]
            except:
                print "friend was missing"
                continue
        new_friend = Friend(user_id, friend_id)
            session.add(new_friend)
        #transaction.commit()
项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def add_result_config():
    session = make_session()
    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    parser.add_argument("match", type=int, help="match id")
    args = parser.parse_args()
    results = results_config

    with transaction.manager:
        for team in results:
            for player in team['players']:
                result_string = "%s,%s" % (team["position"], player["kills"])
                hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == player['name']).first()
                if not hero_id:
                    print "Name wrong"
                    return
                session.add(Result(args.league, hero_id.id, args.match, result_string,
                                   time.time(), 1, 1))
        transaction.commit()
    return
项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def add_result():
    session = make_session()

    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    parser.add_argument("match", type=int, help="match")
    parser.add_argument("player", type=str, help="player name")
    parser.add_argument("position", type=int, help="team position")
    parser.add_argument("kills", type=int, help="player kills")

    args = parser.parse_args()
    with transaction.manager:
        result_string = "%s,%s" % (args.position, args.kills)
        hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == args.player).first()
        if not hero_id:
            print "Name wrong"
            return
        session.add(Result(args.league, hero_id.id, args.match, result_string,
                           time.time(), 1, 1))
        transaction.commit()
    return
项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def main():
    """
    Dont want to delete account as soon as indicated. makes battlecupos and stuff awkward.
    so delete it at the end of the day.
    :return:
    """
    session = make_session()
    with transaction.manager:
        delete_accounts = session.query(User.username).filter(User.to_delete == True).all()
        for username in delete_accounts:
            username = username[0]
            # loop over leagues and delete from them
            #session.query(TeamHero).filter(TeamHero.user == username).delete()
            # any others?
            session.query()
        delete(delete_accounts)
        transaction.commit()
项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def main():
    session = make_session()
    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    args = parser.parse_args()
    league = session.query(League).filter(League.id == args.league).first()
    with transaction.manager:
        print "Updating hero points"
        update_hero_points(session, league)
        transaction.commit()
    with transaction.manager:
        print "Updating league points"
        update_league_points(session, league)
        transaction.commit()
    with transaction.manager:
        print "Updating user rankings"
        update_user_rankings(session, league)
        transaction.commit()
项目:CF401-Project-1---PyListener    作者:PyListener    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession
项目:CF401-Project-1---PyListener    作者:PyListener    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('pylistener.models')``.

    """
    settings = config.get_settings()

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:turingtweets    作者:jjfeore    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession
项目:turingtweets    作者:jjfeore    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('turingtweets.models')``.

    """
    settings = config.get_settings()

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:pyramid_runner    作者:asif-mahmud    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession
项目:pyramid_runner    作者:asif-mahmud    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('{{cookiecutter.project_name}}.models')``.

    """
    settings = config.get_settings()

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:pyramid_runner    作者:asif-mahmud    | 项目源码 | 文件源码
def setUp(self):
        """Defines useful variables and initializes database.

        After this, following variables will be available-
            1. config: Application configuration
            2. engine: DB engine
            3. session: DB session instance
            4. test_app: Test WSGI app
        """
        settings = self.get_settings()
        app = services.main({}, **settings)
        self.test_app = webtest.TestApp(app=app)

        self.config = testing.setUp(settings=settings)

        self.engine = models.get_engine(settings)
        session_factory = models.get_session_factory(self.engine)

        self.session = models.get_tm_session(
            session_factory,
            transaction.manager
        )

        self.__init_database()
项目:pyramid_runner    作者:asif-mahmud    | 项目源码 | 文件源码
def __init_database(self):
        """Initialize the database models.

        Define a method called `init_db` to initialize
        any database instance. This method will automatically
        be called at `setUp`.

        Caution: If `init_db` is defined, a `clean_db` method
        should also be defined which will be called at
        `tearDown`.
        """
        meta.Base.metadata.create_all(self.engine)

        try:
            __init_db = self.__getattribute__('init_db')
            if callable(__init_db):
                with transaction.manager:
                    __init_db()
        except AttributeError:
            pass
项目:pyramid_runner    作者:asif-mahmud    | 项目源码 | 文件源码
def tearDown(self):
        """Calls `pyramid.testing.tearDown` and `transaction.abort`.

        Prior to calling these methods if any `clean_db` method is
        defined, it will be called. Do database clean ups there.
        """
        try:
            __clean_db = self.__getattribute__('clean_db')
            if callable(__clean_db):
                with transaction.manager:
                    __clean_db()
        except AttributeError:
            pass

        testing.tearDown()
        transaction.abort()
项目:peecp    作者:peereesook    | 项目源码 | 文件源码
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)

    engine = get_engine(settings)
    Base.metadata.create_all(engine)

    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)

        model = MyModel(name='one', value=1)
        dbsession.add(model)
项目:peecp    作者:peereesook    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession
项目:peecp    作者:peereesook    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('peecp.models')``.

    """
    settings = config.get_settings()

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:peecp    作者:peereesook    | 项目源码 | 文件源码
def setUp(self):
        self.config = testing.setUp(settings={
            'sqlalchemy.url': 'sqlite:///:memory:'
        })
        self.config.include('.models')
        settings = self.config.get_settings()

        from .models import (
            get_engine,
            get_session_factory,
            get_tm_session,
            )

        self.engine = get_engine(settings)
        session_factory = get_session_factory(self.engine)

        self.session = get_tm_session(session_factory, transaction.manager)
项目:pyramid-zappa-api-boilerplate    作者:web-masons    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession
项目:pyramid-zappa-api-boilerplate    作者:web-masons    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('PyZAPI.models')``.

    """
    settings = config.get_settings()
    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:pyramid-zappa-api-boilerplate    作者:web-masons    | 项目源码 | 文件源码
def setUp(self):
        self.config = testing.setUp(settings={
            'sqlalchemy.url': 'sqlite:///:memory:'
        })
        self.config.include('.models')
        settings = self.config.get_settings()

        from .models import (
            get_engine,
            get_session_factory,
            get_tm_session,
            )

        self.engine = get_engine(settings)
        session_factory = get_session_factory(self.engine)

        self.session = get_tm_session(session_factory, transaction.manager)
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
def data_root():  # type: borgcube.core.models.DataRoot
    """
    Return a `DataRoot` instance.
    """
    try:
        root = _db_local.db.root
    except AttributeError:
        _db_local.db = db()
        root = _db_local.db.root
    try:
        return root.data_root
    except AttributeError:
        with transaction.manager as txn:
            txn.note('Initialized new data root.')
            log.info('Initializing new data root.')
            from borgcube.core.models import DataRoot
            root.data_root = DataRoot()
            return root.data_root
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
def remote_create(self, command_line):
        try:
            self.callx('create', command_line)
        except CalledProcessError as cpe:
            if cpe.returncode == 1:
                log.debug('remote create finished (warning)')
                with transaction.manager as txn:
                    self.job.borg_warning = True
                    txn.note('Set borg warning flag on job %s' % self.job.id)
            else:
                raise
        else:
            log.debug('remote create finished (success)')
        finally:
            transaction.begin()
        self.job.update_state(BackupJob.State.client_in_progress, BackupJob.State.client_done)
项目:peter_sslers    作者:aptise    | 项目源码 | 文件源码
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)

    settings = get_appsettings(config_uri, options=options)

    engine = get_engine(settings)
    Base.metadata.create_all(engine)

    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)
        # model = MyModel(name='one', value=1)
        # dbsession.add(model)
项目:peter_sslers    作者:aptise    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager, keep_session=True)
    return dbsession
项目:peter_sslers    作者:aptise    | 项目源码 | 文件源码
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('peter_sslers.models')``.

    """
    settings = config.get_settings()

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True
    )
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def ensure_transactionless(msg=None, transaction_manager=transaction.manager):
    """Make sure the current thread doesn't already have db transaction in process.

    :param transaction_manager: TransactionManager to check. Defaults to thread local transaction manager.
    """

    txn = transaction_manager._txn

    if txn:
        if not msg:
            msg = "Dangling transction open in transaction.manager. You should not start new one."

        transaction_thread = getattr(transaction.manager, "begin_thread", None)
        logger.fatal("Transaction state management error. Trying to start TX in thread %s. TX started in thread %s", threading.current_thread(), transaction_thread)

        # Destroy the transaction, so if this was a temporary failure in long running process, we don't lock the process up for the good
        txn.abort()

        raise TransactionAlreadyInProcess(msg)
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def main(argv: t.List[str]=sys.argv):
    """Create initial tables for the database specified on the configuration file.

    :param argv: Command line arguments, second one needs to be the uri to a configuration file.
    :raises sys.SystemExit:
    """
    if len(argv) < 2:
        usage_message(argv)

    config_uri = get_config_uri(argv)
    request = init_websauna(config_uri)

    with transaction.manager:
        engine = request.dbsession.get_bind()
        # Always enable UUID extension for PSQL
        # TODO: Convenience for now, because we assume UUIDs, but make this somehow configurable
        engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')

        Base.metadata.create_all(engine)
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_facebook_first_login(web_server, browser, dbsession):
    """Login an user."""

    b = browser
    b.visit(web_server)

    b.click_link_by_text("Sign in")

    assert b.is_element_visible_by_css("#login-form")

    b.find_by_css(".btn-login-facebook").click()
    do_facebook_login_if_facebook_didnt_log_us_already(browser)
    assert b.is_element_present_by_css("#msg-you-are-logged-in")

    # See that we got somewhat sane data
    with transaction.manager:
        assert dbsession.query(User).count() == 1
        u = dbsession.query(User).get(1)
        assert u.first_login
        assert u.email == os.environ["FACEBOOK_USER"]
        assert u.is_admin()  # First user becomes admin
        assert u.activated_at

    b.find_by_css("#nav-logout").click()
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_facebook_login_disabled_user(web_server, browser, dbsession, init):
    """Logged in user which is not enabled should give an error.."""

    with transaction.manager:
        u = create_user(dbsession, init.config.registry, email=os.environ["FACEBOOK_USER"])
        u.enabled = False

    b = browser
    b.visit(web_server)

    b.click_link_by_text("Sign in")

    assert b.is_element_visible_by_css("#login-form")

    b.find_by_css(".btn-login-facebook").click()

    do_facebook_login_if_facebook_didnt_log_us_already(browser)

    assert b.is_element_present_by_css("#msg-cannot-login-social-media-user")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_transaction_aware_task_success(celery_worker, task_app_request, dbsession, demo_user):
    """Transaction aware tasks works in eager mode.."""
    with transaction.manager:
        # Do a dummy database write
        u = dbsession.query(User).first()

        demotasks.modify_username.apply_async([u.id], tm=transaction.manager)
        # Let the task travel in Celery queue
        time.sleep(2.0)

        # Task should not fire unless we exit the transaction
        assert u.username != "set by celery"

    # Let the transaction commit
    time.sleep(0.5)

    # Task has now fired after transaction was committed
    with transaction.manager:
        u = dbsession.query(User).get(1)
        assert u.username == "set by celery"
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_transaction_manager_abort(celery_worker, task_app_request, dbsession, demo_user):
    """Test that transaction are not executed to schedule if transaction manager aborts."""

    try:
        # Tasks do not execute if transaction is never commit because of exception
        with transaction.manager:
            assert dbsession.query(User).count() == 1
            assert dbsession.query(User).get(1).username == "test"
            demotasks.modify_username.apply_async(args=[1], tm=transaction.manager)
            raise RuntimeError("aargh")
    except RuntimeError:
        pass

    # Let the transaction commit (which should not happen)
    time.sleep(0.5)

    # Because of exception, Celery never fires
    with transaction.manager:
        u = dbsession.query(User).get(1)
        assert u.username == "test"
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_manual_transaction(celery_worker, task_app_request, dbsession, demo_user):
    """Manual transaction lifecycles within task work."""

    with transaction.manager:
        # Do a dummy database write
        u = dbsession.query(User).first()

        demotasks.modify_username_manual_transaction.apply_async(kwargs={"user_id": u.id}, tm=transaction.manager)
        # Let the task travel in Celery queue
        time.sleep(1.0)

        # Task should not fire unless we exit the transaction
        assert u.username != "set by celery"

    # Let the transaction commit
    time.sleep(0.5)

    # Task has now fired after transaction was committed
    with transaction.manager:
        u = dbsession.query(User).first()
        assert u.username == "set by celery"
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_login(web_server, browser, dbsession, init):
    """Login an user."""

    with transaction.manager:
        create_user(dbsession, init.config.registry)

    b = browser
    b.visit(web_server)

    b.click_link_by_text("Sign in")

    assert b.is_element_present_by_css("#login-form")

    b.fill("username", EMAIL)
    b.fill("password", PASSWORD)
    b.find_by_name("login_email").click()

    # After login we see a profile link to our profile
    assert b.is_element_present_by_css("#nav-logout")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_logout(web_server, browser, dbsession, init):
    """Log out."""

    with transaction.manager:
        create_user(dbsession, init.config.registry)

    b = browser
    b.visit("{}/{}".format(web_server, "login"))

    assert b.is_element_present_by_css("#login-form")

    b.fill("username", EMAIL)
    b.fill("password", PASSWORD)
    b.find_by_name("login_email").click()

    assert b.is_element_present_by_css("#msg-you-are-logged-in")
    b.find_by_css("#nav-logout").click()

    # Anonynous again
    assert b.is_element_present_by_css("#msg-logged-out")
    assert not b.is_element_present_by_css("#nav-logout")

    # We should see the log in form
    assert b.is_element_present_by_css("#login-form")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_forget_password_disabled_user(web_server, browser, dbsession, init):
    """Reset password by email."""

    with transaction.manager:
        u = create_user(dbsession, init.config.registry)
        u.enabled = False

    b = browser
    b.visit(web_server + "/login")

    assert b.is_element_present_by_css("#login-form")

    b.click_link_by_text("Forgot your password?")
    assert b.is_element_present_by_css("#forgot-password-form")
    b.fill("email", EMAIL)
    b.find_by_name("submit").click()

    assert b.is_element_present_by_css("#msg-cannot-reset-password")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_login_forget_password_email_send(web_server, browser, dbsession, init):
    """Send out the reset password by email, but do not answer to it, instead directly login."""

    with transaction.manager:
        create_user(dbsession, init.config.registry)

    b = browser
    b.visit(web_server)

    b.find_by_css("#nav-sign-in").click()

    assert b.is_element_present_by_css("#login-form")

    b.click_link_by_text("Forgot your password?")
    assert b.is_element_present_by_css("#forgot-password-form")
    b.fill("email", EMAIL)
    b.find_by_name("submit").click()

    b.visit("{}/login".format(web_server))

    b.fill("username", EMAIL)
    b.fill("password", PASSWORD)
    b.find_by_name("login_email").click()
    assert b.is_element_present_by_css("#msg-you-are-logged-in")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_forget_password_expired_token(web_server, browser, dbsession, init):
    """Reset password by email."""

    with transaction.manager:
        create_user(dbsession, init.config.registry)

    b = browser
    b.visit(web_server + "/forgot-password")

    assert b.is_element_present_by_css("#forgot-password-form")
    b.fill("email", EMAIL)
    b.find_by_name("submit").click()

    assert b.is_element_present_by_css("#msg-check-email")

    with transaction.manager:
        user = get_user(dbsession)
        activation = user.activation
        activation.expires_at = now() - timedelta(days=365)
        activation_code = activation.code

    b.visit("{}/reset-password/{}".format(web_server, activation_code))
    assert b.is_element_present_by_css("#not-found")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_enter_admin(web_server, browser, dbsession, init):
    """The first user can open the admin page."""

    with transaction.manager:
        u = create_user(dbsession, init.config.registry)
        site_creator = get_site_creator(init.config.registry)
        site_creator.init_empty_site(dbsession, u)
        assert u.is_admin()

    b = browser
    b.visit(web_server + "/login")

    b.fill("username", EMAIL)
    b.fill("password", PASSWORD)
    b.find_by_name("login_email").click()

    assert b.is_element_visible_by_css("#nav-admin")
    b.find_by_css("#nav-admin").click()

    assert b.is_element_present_by_css("#admin-main")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def create_logged_in_user(dbsession:Session, registry:Registry, web_server:str, browser:DriverAPI, admin:bool=False, email:str=EMAIL, password:str=PASSWORD):
    """For a web browser test session, creates a new user and log it in inside the test browser."""

    # Catch some common argument misordering issues
    assert isinstance(registry, Registry)
    assert isinstance(web_server, str)

    with transaction.manager:
        create_user(dbsession, registry, admin=admin, email=email, password=password)

    b = browser
    b.visit("{}/{}".format(web_server, "login"))

    assert b.is_element_present_by_css("#login-form")

    b.fill("username", email)
    b.fill("password", password)
    b.find_by_name("login_email").click()

    # After login we log out link to confirm login has succeeded
    assert b.is_element_present_by_css("#nav-logout")
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def test_add_choice_choose_no_question(browser: DriverAPI, registry, web_server, dbsession):

    from .tutorial import Question
    from .tutorial import Choice

    with transaction.manager:
        q = Question(question_text="What is love")
        dbsession.add(q)
        dbsession.flush()

    b = browser
    create_logged_in_user(dbsession, registry, web_server, browser, admin=True)

    b.visit(web_server)
    b.find_by_css("#nav-admin").click()
    b.find_by_css("#btn-panel-add-choice").click()
    b.fill("choice_text", "Baby don't hurt me")
    b.find_by_name("add").click()

    assert b.is_element_present_by_css("#msg-item-added")

    with transaction.manager:
        assert dbsession.query(Choice).first().question is None
项目:assignment_aa    作者:RaHus    | 项目源码 | 文件源码
def get_tm_session(session_factory, transaction_manager):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = get_tm_session(session_factory, transaction.manager)

    """
    dbsession = session_factory()
    zope.sqlalchemy.register(
        dbsession, transaction_manager=transaction_manager)
    return dbsession