當前位置: 首頁>>代碼示例>>Python>>正文


Python orm.Session方法代碼示例

本文整理匯總了Python中sqlalchemy.orm.Session方法的典型用法代碼示例。如果您正苦於以下問題:Python orm.Session方法的具體用法?Python orm.Session怎麽用?Python orm.Session使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sqlalchemy.orm的用法示例。


在下文中一共展示了orm.Session方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_session

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def get_session():
    """
        Return SQLAlchemy session
    """

    global sessions

    if global_scope['db_file'] is None:
        raise RuntimeError('`db_file` is not defined in the global scope')

    # Create a unique key for the db session
    db_file = global_scope['db_file']

    # Add a session to the current list
    if not sessions.get(db_file):
        sessions[db_file] = Session(bind=get_engine())

    return sessions[db_file] 
開發者ID:gabfl,項目名稱:vault,代碼行數:20,代碼來源:base.py

示例2: __init__

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def __init__(
        self,
        settings: SQLAlchemySettings,
        base: DeclarativeMeta = Base,
        tables: Optional[Sequence] = None,
        connection_strategy: str = "plain",
        session: Optional[Union[Session, scoped_session]] = None,
    ):
        super(SQLAlchemyDatastore, self).__init__(settings=settings)
        self._was_session_created_here = False
        self._session = session
        if session:
            self._engine: Optional[Engine] = session.get_bind()
        else:
            self._engine = None
        self._base = base
        self._tables = tables
        self._connection_strategy = connection_strategy 
開發者ID:johnbywater,項目名稱:eventsourcing,代碼行數:20,代碼來源:datastore.py

示例3: upgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def upgrade():
    conn = op.get_bind()
    session = Session(bind=conn)

    op.alter_column('user', 'password_hash',
           existing_type=sa.VARCHAR(length=128),
           type_=sa.VARCHAR(length=200),
           existing_nullable=False)
    op.alter_column('user', 'pin_hash',
           existing_type=sa.VARCHAR(),
           type_=sa.VARCHAR(length=200),
           existing_nullable=False)
    session.commit()

    f = Fernet(current_app.config['PASSWORD_PEPPER'])
    for user in session.query(User).execution_options(show_all=True).all():
        if user.password_hash:
            user.password_hash = f.encrypt(user.password_hash.encode()).decode()
        if user.pin_hash:
            user.pin_hash = f.encrypt(user.pin_hash.encode()).decode()
    session.commit() 
開發者ID:teamsempo,項目名稱:SempoBlockchain,代碼行數:23,代碼來源:87b723e167d3_.py

示例4: downgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def downgrade():
    conn = op.get_bind()
    session = Session(bind=conn)

    f = Fernet(current_app.config['PASSWORD_PEPPER'])

    for user in session.query(User).execution_options(show_all=True).all():
        if user.password_hash:
            user.password_hash = f.decrypt(user.password_hash.encode()).decode()
        if user.pin_hash:
            user.pin_hash = f.decrypt(user.pin_hash.encode()).decode()
    session.commit()

    op.alter_column('user', 'password_hash',
           existing_type=sa.VARCHAR(length=200),
           type_=sa.VARCHAR(length=128),
           existing_nullable=False)
    op.alter_column('user', 'pin_hash',
           existing_type=sa.VARCHAR(length=200),
           type_=sa.VARCHAR(),
           existing_nullable=False)
    session.commit() 
開發者ID:teamsempo,項目名稱:SempoBlockchain,代碼行數:24,代碼來源:87b723e167d3_.py

示例5: upgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def upgrade():
    conn = op.get_bind()
    session = Session(bind=conn)

    op.add_column('organisation', sa.Column('external_auth_username', sa.String(), nullable=True))
    op.add_column('organisation', sa.Column('_external_auth_password', sa.String(), nullable=True))

    tcr = sa.sql.table('organisation',
                       sa.Column('id', sa.Integer, primary_key=True),
                       sa.Column('external_auth_username', sa.String(), nullable=True),
                       sa.Column('_external_auth_password', sa.String(), nullable=True),
                       sa.Column('name', sa.String(), nullable=True))

    for org in session.query(tcr).execution_options(show_all=True).all():
        org.external_auth_username = 'admin_'+(org.name or '').lower().replace(' ', '_')
        org._external_auth_password = encrypt_string(secrets.token_hex(16))
    session.commit() 
開發者ID:teamsempo,項目名稱:SempoBlockchain,代碼行數:19,代碼來源:961ab9adc300_.py

示例6: mongoquery

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def mongoquery(cls, query_or_session: Union[Query, Session] = None) -> MongoQuery:
        """ Build a MongoQuery

        Note that when `None` is given, the resulting Query is not bound to any session!
        You'll have to bind it manually, after calling .end()

        :param query_or_session: Query to start with, or a session object to initiate the query with
        :type query_or_session: sqlalchemy.orm.Query | sqlalchemy.orm.Session | None
        :rtype: mongosql.MongoQuery
        """
        if query_or_session is None:
            query = Query([cls])
        elif isinstance(query_or_session, Session):
            query = query_or_session.query(cls)
        elif isinstance(query_or_session, Query):
            query = query_or_session
        else:
            raise ValueError('Argument must be Query or Session')

        return cls._get_mongoquery().from_query(query) 
開發者ID:kolypto,項目名稱:py-mongosql,代碼行數:22,代碼來源:sa.py

示例7: upgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def upgrade():
    try:
        with op.batch_alter_table("smsgatewayoption") as batch_op:
            batch_op.drop_constraint('sgix_1', type_='unique')
            batch_op.create_unique_constraint('sgix_1', ['gateway_id', 'Key', 'Type'])
    except Exception as exx:
        print("Cannot change constraint 'sgix_1' in table smsgatewayoption.")
        print(exx)

    try:
        bind = op.get_bind()
        session = orm.Session(bind=bind)
        # add default type 'option' for all rows
        for row in session.query(SMSGatewayOption):
            if not row.Type:
                row.Type = "option"

    except Exception as exx:
        session.rollback()
        print("Failed to add option type for all existing entries in table smsgatewayoption!")
        print(exx)

    session.commit() 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:25,代碼來源:e360c56bcf8c_.py

示例8: upgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def upgrade():
    try:
        op.add_column('policy', sa.Column('adminuser', sa.Unicode(length=256), nullable=True))
    except Exception as exx:
        print('Adding of column "adminuser" in table policy failed: {!r}'.format(exx))
        print('This is expected behavior if this column already exists.')

    # Now that we added the column in the table, we can move the "user" from admin-policies to
    # the "adminuser" column

    try:
        bind = op.get_bind()
        session = orm.Session(bind=bind)
        pol_name = None
        for policy in session.query(Policy).filter(Policy.user != "", Policy.scope == "admin"):
            pol_name = policy.name
            # move the "user" to the "adminuser"
            policy.adminuser = policy.user
            policy.user = u""
        session.commit()
    except Exception as exx:
        session.rollback()
        print("Failed to migrate column adminuser in policies due to error in policy '{0!s}'.".format(pol_name))
        print(exx) 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:26,代碼來源:a7e91b18a460_.py

示例9: do_import_licenses

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def do_import_licenses(file_data: List[dict]):
    imported = set()
    print("Importing licenses ... ", flush=True)
    with progressbar.ProgressBar(max_value=len(file_data)) as bar:
        for idx, p in enumerate(file_data):
            info = p.get('info')
            license_text = detect_license(info.get('license'))

            if license_text and license_text not in imported:
                imported.add(license_text)
                session: Session = DbSession.factory()

                package_license = License()
                package_license.id = license_text
                package_license.description = info.get('license')

                session.add(package_license)
                session.commit()

            bar.update(idx)

    sys.stderr.flush()
    sys.stdout.flush() 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:25,代碼來源:load_data.py

示例10: do_user_import

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def do_user_import(user_lookup: Dict[str, str]) -> Dict[str, User]:
    print("Importing users ... ", flush=True)
    with progressbar.ProgressBar(max_value=len(user_lookup)) as bar:
        for idx, (email, name) in enumerate(user_lookup.items()):
            session: Session = DbSession.factory()
            session.expire_on_commit = False

            user = User()
            user.email = email
            user.name = name
            session.add(user)

            session.commit()
            bar.update(idx)

    print()
    sys.stderr.flush()
    sys.stdout.flush()

    session: Session = DbSession.factory()
    return {u.email: u for u in session.query(User)} 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:23,代碼來源:load_data.py

示例11: upgrade

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import Session [as 別名]
def upgrade():
    bind = op.get_bind()
    session = Session(bind=bind)

    department_query = text("SELECT * FROM departments")
    for department in session.execute(department_query):
        short_name = "".join([x[0] for x in department.name.split(" ")])
        department.short_name = short_name
    session.commit()

    op.alter_column('departments', 'short_name', existing_type=sa.VARCHAR(length=80), nullable=False) 
開發者ID:codeforamerica,項目名稱:comport,代碼行數:13,代碼來源:51524883509_.py


注:本文中的sqlalchemy.orm.Session方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。