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


Python orm.scoped_session方法代码示例

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


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

示例1: set_session

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def set_session(application: Flask, DB_SESSION: scoped_session) -> Iterator:
    """
    Set the Database Session for the app before it is run in main.py.
    :param application: Flask app object
            <flask.app.Flask>
    :param DB_SESSION: SQLalchemy Session object
            <sqlalchemy.orm.session.Session>

    Raises:
        TypeError: If `DB_SESSION` is not an instance of `scoped_session` or `Session`.

    """
    if not isinstance(DB_SESSION, scoped_session) and not isinstance(
            DB_SESSION, Session):
        raise TypeError(
            "The API Doc is not of type <sqlalchemy.orm.session.Session> or"
            " <sqlalchemy.orm.scoping.scoped_session>")

    def handler(sender: Flask, **kwargs: Any) -> None:
        g.dbsession = DB_SESSION
    with appcontext_pushed.connected_to(handler, application):
        yield 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:24,代码来源:utils.py

示例2: setUpClass

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def setUpClass(self):
        """Database setup before the CRUD tests."""
        print("Creating a temporary datatbsse...")
        engine = create_engine('sqlite:///:memory:')
        Base.metadata.create_all(engine)
        session = scoped_session(sessionmaker(bind=engine))
        self.API_NAME = "demoapi"
        self.HYDRUS_SERVER_URL = "http://hydrus.com/"
        self.session = session

        self.doc = doc_maker.create_doc(
            doc, self.HYDRUS_SERVER_URL, self.API_NAME)

        test_classes = doc_parse.get_classes(self.doc.generate())

        # Getting list of classes from APIDoc
        self.doc_collection_classes = [
            self.doc.collections[i]["collection"].class_.title for i in self.doc.collections]
        print(self.doc_collection_classes)
        print(random.choice(self.doc_collection_classes))
        test_properties = doc_parse.get_all_properties(test_classes)
        doc_parse.insert_classes(test_classes, self.session)
        doc_parse.insert_properties(test_properties, self.session)
        print("Classes and properties added successfully.")
        print("Setup done, running tests...") 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:27,代码来源:test_crud.py

示例3: __init__

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_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

示例4: __init__

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def __init__(self, config=None):
        super(Audit, self).__init__(config)
        self.name = "sqlaudit"
        self.sign_data = not self.config.get("PI_AUDIT_NO_SIGN")
        self.sign_object = None
        self.verify_old_sig = self.config.get('PI_CHECK_OLD_SIGNATURES')
        if self.sign_data:
            self.read_keys(self.config.get("PI_AUDIT_KEY_PUBLIC"),
                           self.config.get("PI_AUDIT_KEY_PRIVATE"))
            self.sign_object = Sign(self.private, self.public)

        # We can use "sqlaudit" as the key because the SQLAudit connection
        # string is fixed for a running privacyIDEA instance.
        # In other words, we will not run into any problems with changing connect strings.
        self.engine = get_engine(self.name, self._create_engine)
        # create a configured "Session" class. ``scoped_session`` is not
        # necessary because we do not share session objects among threads.
        # We use it anyway as a safety measure.
        Session = scoped_session(sessionmaker(bind=self.engine))
        self.session = Session()
        # Ensure that the connection gets returned to the pool when the request has
        # been handled. This may close an already-closed session, but this is not a problem.
        register_finalizer(self.session.close)
        self.session._model_changes = {} 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:26,代码来源:sqlaudit.py

示例5: _index_preshot

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def _index_preshot(self):
        logger.info('Index preshot')
        # BEGIN DB update
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        for acct in data_sess.query(Account).all():
            end_bal = acct.balance.ledger
            pctrange = float(end_bal) * 0.1
            for i in range(1, 30):
                dt = dtnow() - timedelta(days=i)
                b = end_bal + Decimal(uniform(-1 * pctrange, pctrange))
                b = Decimal(b.quantize(Decimal('.001'), rounding=ROUND_HALF_UP))
                acct.set_balance(ledger=b, ledger_date=dt, overall_date=dt)
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        # END DB update
        self.get('/')
        sleep(1) 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:24,代码来源:make_screenshots.py

示例6: _index_postshot

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def _index_postshot(self):
        logger.info('Index postshot')
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        for acct_id in [2, 5]:
            acct = data_sess.query(Account).get(acct_id)
            s = acct.ofx_statement
            s.as_of = dtnow()
            data_sess.add(s)
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        logger.info('Done updating DB (index postshot)') 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:18,代码来源:make_screenshots.py

示例7: _balance_postshot

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def _balance_postshot(self):
        logger.info('Balance postshot')
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        for t in data_sess.query(Transaction).filter(
            Transaction.id.__ge__(4)
        ).all():
            data_sess.delete(t)
        data_sess.flush()
        data_sess.commit()
        for b in data_sess.query(Budget).filter(
            Budget.id.__ge__(7)
        ).all():
            data_sess.delete(b)
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        logger.info('Done updating DB') 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:23,代码来源:make_screenshots.py

示例8: _credit_payoff_preshot

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def _credit_payoff_preshot(self):
        logger.info('credit payoff preshot - DB update')
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        acct = data_sess.query(Account).get(4)
        stmt = data_sess.query(OFXStatement).get(7)
        txn = OFXTransaction(
            account=acct,
            statement=stmt,
            fitid='%s-MANUAL-CCPAYOFF' % dtnow().strftime('%Y%m%d%H%M%S'),
            trans_type='debit',
            date_posted=stmt.as_of,
            amount=Decimal('46.9061'),
            name='Interest Charged - MANUALLY ENTERED',
            is_interest_charge=True
        )
        data_sess.add(txn)
        data_sess.commit()
        data_sess.close()
        conn.close()
        logger.info('credit payoff preshot done')
        self.get('/accounts/credit-payoff') 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:26,代码来源:make_screenshots.py

示例9: _refreshdb

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def _refreshdb(self):
        """
        Refresh/Load DB data before tests
        """
        if 'NO_REFRESH_DB' in os.environ:
            logger.info('Skipping session-scoped DB refresh')
            return
        # setup the connection
        conn = engine.connect()
        logger.info('Refreshing DB (session-scoped)')
        # clean the database
        biweeklybudget.models.base.Base.metadata.reflect(engine)
        biweeklybudget.models.base.Base.metadata.drop_all(engine)
        biweeklybudget.models.base.Base.metadata.create_all(engine)
        # load the sample data
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        SampleDataLoader(data_sess).load()
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        logger.info('DB refreshed.') 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:26,代码来源:make_screenshots.py

示例10: setup_class

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def setup_class(cls):
        wsgiapp = middleware.make_app(config['global_conf'], **config)
        cls.app = paste.fixture.TestApp(wsgiapp)
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        p.load('datastore')
        p.load('datapusher')
        p.load('test_datapusher_plugin')

        resource = factories.Resource(url_type='datastore')
        cls.dataset = factories.Dataset(resources=[resource])

        cls.sysadmin_user = factories.User(name='testsysadmin', sysadmin=True)
        cls.normal_user = factories.User(name='annafan')
        engine = db._get_engine(
            {'connection_url': config['ckan.datastore.write_url']})
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine)) 
开发者ID:italia,项目名称:daf-recipes,代码行数:19,代码来源:test_interfaces.py

示例11: setup_class

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def setup_class(cls):
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        p.load('datastore')
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        resource = model.Package.get('annakarenina').resources[0]
        cls.data = {
            'resource_id': resource.id,
            'aliases': u'b\xfck2',
            'fields': [{'id': 'book', 'type': 'text'},
                       {'id': 'author', 'type': 'text'},
                       {'id': 'rating with %', 'type': 'text'}],
            'records': [{'book': 'annakarenina', 'author': 'tolstoy',
                         'rating with %': '90%'},
                        {'book': 'warandpeace', 'author': 'tolstoy',
                         'rating with %': '42%'}]
        }

        engine = db._get_engine(
            {'connection_url': config['ckan.datastore.write_url']})
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
        set_url_type(
            model.Package.get('annakarenina').resources, cls.sysadmin_user) 
开发者ID:italia,项目名称:daf-recipes,代码行数:27,代码来源:test_delete.py

示例12: make_session

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def make_session(engines, force_scope=False, info=None):
    if force_scope:
        scopefunc = scope_func
    else:
        scopefunc = None

    session = scoped_session(
        sessionmaker(
            class_=RoutingSession,
            expire_on_commit=False,
            engines=engines,
            info=info or {"name": uuid.uuid4().hex},
        ),
        scopefunc=scopefunc
    )
    return session 
开发者ID:MrKiven,项目名称:ECache,代码行数:18,代码来源:db.py

示例13: remove_stale_modification_records

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def remove_stale_modification_records(session: scoped_session,
                                      stale_records_removal_interval: int=900):
    """
    Remove modification records which are older than last 1000 records.
    :param session: sqlalchemy session.
    :param stale_records_removal_interval: Interval time to run the removal job.
    """
    timer = Timer(stale_records_removal_interval,
                  remove_stale_modification_records, [session])
    timer.daemon = True
    timer.start()
    # Get all valid records.
    valid_records = session.query(Modification).order_by(
        Modification.job_id.desc()).limit(1000).all()
    # If number of returned valid records is less than set limit then
    # there is nothing to clean up.
    if len(valid_records) < 1000:
        return
    else:
        # Get the job_id of last (oldest) valid record.
        job_id_of_last_valid_record = valid_records[-1].job_id
        # Get all records which are older than the oldest valid record.
        stale_records = session.query(Modification).filter(
            Modification.job_id < job_id_of_last_valid_record).all()
        for record in stale_records:
            session.delete(record)
        session.commit()
    session.remove() 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:30,代码来源:stale_records_cleanup.py

示例14: insert_classes

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def insert_classes(classes: List[Dict[str, Any]],
                   session: scoped_session) -> Optional[Any]:
    """Insert all the classes as defined in the APIDocumentation into DB.

    Raises:
        TypeError: If `session` is not an instance of `scoped_session` or `Session`.

    """
    # print(session.query(exists().where(RDFClass.name == "Datastream")).scalar())
    if not isinstance(session, scoped_session) and not isinstance(
            session, Session):
        raise TypeError(
            "session is not of type <sqlalchemy.orm.scoping.scoped_session>"
            "or <sqlalchemy.orm.session.Session>"
        )
    class_list = [RDFClass(name=class_["label"].strip('.')) for class_ in classes
                  if "label" in class_ and
                  not session.query(exists().where(RDFClass.name == class_["label"]
                                                   .strip('.'))).scalar()]

    class_list.extend([RDFClass(name=class_["title"].strip('.')) for class_ in classes
                       if "title" in class_ and
                       not session.query(exists().where(RDFClass.name == class_["title"]
                                                                .strip('.'))).scalar()])
    # print(class_list)
    session.add_all(class_list)
    session.commit()
    return None 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:30,代码来源:doc_parse.py

示例15: insert_properties

# 需要导入模块: from sqlalchemy import orm [as 别名]
# 或者: from sqlalchemy.orm import scoped_session [as 别名]
def insert_properties(properties: Set[str],
                      session: scoped_session) -> Optional[Any]:
    """Insert all the properties as defined in the APIDocumentation into DB."""
    prop_list = [BaseProperty(name=prop) for prop in properties
                 if not session.query(exists().where(BaseProperty.name == prop)).scalar()]
    session.add_all(prop_list)
    session.commit()
    return None


# if __name__ == "__main__":
#     Session = sessionmaker(bind=engine)
#     session = Session()
#
#     doc = doc_gen("test", "test")
#     # Extract all classes with supportedProperty from both
#     classes = get_classes(doc.generate())
#
#     # Extract all properties from both
#     # import pdb; pdb.set_trace()
#     properties = get_all_properties(classes)
#     # Add all the classes
#     insert_classes(classes, session)
#     print("Classes inserted successfully")
#     # Add all the properties
#     insert_properties(properties, session)
#     print("Properties inserted successfully") 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:29,代码来源:doc_parse.py


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