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


Python orm.sessionmaker方法代碼示例

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


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

示例1: setUpClass

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [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

示例2: main

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def main(args, env):
    global Session

    if args.verbose >= 1:
        app.config['DEBUG'] = True
    sys.stderr.write("connecting to DB server {:s}\n".format(args.db))
    connection_succeeded = False
    while not connection_succeeded:
        try:
            engine = create_engine(args.db)
            Session = sessionmaker(bind = engine)
            Base.metadata.create_all(engine)
            sys.stderr.write("connection succeeded!\n")
            connection_succeeded = True
            app.run(debug = args.verbose >= 1, host = "0.0.0.0", port = 80)
        except OperationalError as err:
            if "Connection refused" in str(err):
                connection_succeeded = False
                time.sleep(10)
            else:
                raise 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:23,代碼來源:server.py

示例3: open

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def open(self,database):
    """
    params:
        database: str. Database to be opered. The path should be included
    """
    assert(database[-4:]=='.mdo')
    if not os.path.exists(database):
        self._create(database)
    operate_db=database[:-4]+'.op'
    shutil.copy(database,operate_db)
#        engine=create_engine('sqlite:///:memory:')
    engine=create_engine('sqlite:///'+operate_db) #should be run in memory in the future
    Session=o.sessionmaker(bind=engine)
    self.session=Session()
    self.__operate_db=operate_db
    self.__storage_db=database 
開發者ID:zhuoju36,項目名稱:StructEngPy,代碼行數:18,代碼來源:db.py

示例4: __init__

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def __init__(self, user, password, database, host, port):
        driver = 'mysql+pymysql'

        self.url = URL(driver, user, password, host, port, database)

        # Hack to establish SSL connection (see #231)
        try:
            self._engine = create_engine(self.url, echo=True,
                                         connect_args={'ssl': {'activate': True}})
            self._engine.connect().close()
        except InternalError:
            self._engine = create_engine(self.url, echo=True)

        self._Session = sessionmaker(bind=self._engine)

        # Create the schema on the database.
        # It won't replace any existing schema
        ModelBase.metadata.create_all(self._engine) 
開發者ID:chaoss,項目名稱:grimoirelab-sortinghat,代碼行數:20,代碼來源:test_model.py

示例5: setUpClass

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def setUpClass(cls):
        # Set db location
        file_ = tempfile.NamedTemporaryFile(delete=False)
        global_scope['db_file'] = file_.name

        # Create a user key
        cls.secret_key = str(uuid.uuid4())
        cls.enc = global_scope['enc'] = Encryption(cls.secret_key.encode())

        # Load config
        cls.conf_path = tempfile.TemporaryDirectory()
        cls.config = Config(cls.conf_path.name + '/config')
        global_scope['conf'] = cls.config

        # Create engine
        engine = get_engine()

        # Create tables and set database session
        Base.metadata.create_all(engine)
        Session = sessionmaker(bind=engine)
        cls.session = Session()

        # Populate db
        cls.populate_base() 
開發者ID:gabfl,項目名稱:vault,代碼行數:26,代碼來源:base.py

示例6: __init__

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def __init__(self, results_queue, thread_pool, use_file=True, use_database=True, filename="proxy-ip-list.csv"):
        self.use_file = use_file
        self.use_database = use_database
        self.filename = filename
        self.results_queue = results_queue
        self.thread_pool = thread_pool

        if use_database:
            try:
                cf = ConfigParser.ConfigParser()
                cf.read("config.ini")
                db_name = cf.get("Pansidong", "database")
                username = cf.get(db_name, "username")
                password = cf.get(db_name, "password")
                host = cf.get(db_name, "host")
                database = cf.get(db_name, "database")
            except AttributeError, e:
                logger.fatal(e.message)
                sys.exit(1)
            self.engine = create_engine("mysql://" + username + ":" + password + "@" +
                                        host + "/" + database + "?charset=utf8")
            self.db_session = sessionmaker(bind=self.engine)
            self.session = self.db_session() 
開發者ID:lightless233,項目名稱:Pansidong,代碼行數:25,代碼來源:SaveData.py

示例7: write

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def write(self):
        Session = sessionmaker(bind=droidsql.engine)
        session = Session()
        sample = droidsql.Sample(sha256=self.sha256, \
                                 sanitized_basename=self.sanitized_basename, \
                                 file_nb_classes=self.file_nb_classes, \
                                 file_nb_dir=self.file_nb_dir,\
                                 file_size=self.file_size,\
                                 file_small=self.file_small,\
                                 filetype=self.filetype,\
                                 file_innerzips=self.file_innerzips,\
                                 manifest_properties=json.dumps(self.manifest), \
                                 smali_properties=json.dumps(self.smali),\
                                 wide_properties=json.dumps(self.wide),\
                                 arm_properties=json.dumps(self.arm),\
                                 dex_properties=json.dumps(self.dex),\
                                 kits=json.dumps(self.kits))
        session.add(sample)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError:
            # occurs when the sample with the same sha256 is already in
            if self.verbose:
                print("Sample is already in the database") 
開發者ID:cryptax,項目名稱:droidlysis,代碼行數:26,代碼來源:droidproperties.py

示例8: init_db

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def init_db(app_db_path):
    # Open session for database connection
    global session
    global app_DB_path

    app_DB_path = app_db_path
    engine = create_engine(u'sqlite:///{0}'.format(app_db_path), echo=False)

    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()

    if os.path.exists(app_db_path):
        Base.metadata.create_all(engine)
        migrate_Database(session)
        clean_database(session)
    else:
        Base.metadata.create_all(engine)
        create_admin_user(session)
        create_anonymous_user(session) 
開發者ID:janeczku,項目名稱:calibre-web,代碼行數:22,代碼來源:ub.py

示例9: _accept_with

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def _accept_with(cls, target):
        if isinstance(target, scoped_session):

            target = target.session_factory
            if not isinstance(target, sessionmaker) and \
                (
                    not isinstance(target, type) or
                    not issubclass(target, Session)
            ):
                raise exc.ArgumentError(
                    "Session event listen on a scoped_session "
                    "requires that its creation callable "
                    "is associated with the Session class.")

        if isinstance(target, sessionmaker):
            return target.class_
        elif isinstance(target, type):
            if issubclass(target, scoped_session):
                return Session
            elif issubclass(target, Session):
                return target
        elif isinstance(target, Session):
            return target
        else:
            return None 
開發者ID:jpush,項目名稱:jbox,代碼行數:27,代碼來源:events.py

示例10: init_database

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def init_database(self):
        self.raw_db = create_engine(self.config['url'], echo=False)
        self.raw_conn = self.raw_db.connect()
        self.operations = Operations(self.raw_conn, self.config)

        try:
            self.raw_conn.connection.set_isolation_level(0)
        except AttributeError:
            logger.info('Could not set isolation level to 0')

        self.db = create_engine(self.config['stellar_url'], echo=False)
        self.db.session = sessionmaker(bind=self.db)()
        self.raw_db.session = sessionmaker(bind=self.raw_db)()
        tables_missing = self.create_stellar_database()

        self.create_stellar_tables()

        # logger.getLogger('sqlalchemy.engine').setLevel(logger.WARN) 
開發者ID:fastmonkeys,項目名稱:stellar,代碼行數:20,代碼來源:app.py

示例11: get_db_session_factory

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def get_db_session_factory(provider: str,
                           db_name: str = None,
                           data_schema: object = None):
    """
    get db session factory of the (provider,db_name) or (provider,data_schema)

    :param provider:
    :type provider:
    :param db_name:
    :type db_name:
    :param data_schema:
    :type data_schema:
    :return:
    :rtype:
    """
    if data_schema:
        db_name = get_db_name(data_schema=data_schema)

    session_key = '{}_{}'.format(provider, db_name)
    session = zvt_context.db_session_map.get(session_key)
    if not session:
        session = sessionmaker()
        zvt_context.db_session_map[session_key] = session
    return session 
開發者ID:zvtvz,項目名稱:zvt,代碼行數:26,代碼來源:api.py

示例12: __init__

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [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

示例13: reflect_hints_db

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def reflect_hints_db(db_path):
    """
    Reflect the database schema of the hints database, automapping the existing tables

    The NullPool is used to avoid concurrency issues with luigi. Using this activates pooling, but since sqlite doesn't
    really support pooling, what effectively happens is just that it locks the database and the other connections wait.

    :param db_path: path to hints sqlite database
    :return: sqlalchemy.MetaData object, sqlalchemy.orm.Session object
    """
    engine = sqlalchemy.create_engine('sqlite:///{}'.format(db_path), poolclass=NullPool)
    metadata = sqlalchemy.MetaData()
    metadata.reflect(bind=engine)
    Base = automap_base(metadata=metadata)
    Base.prepare()
    speciesnames = Base.classes.speciesnames
    seqnames = Base.classes.seqnames
    hints = Base.classes.hints
    featuretypes = Base.classes.featuretypes
    Session = sessionmaker(bind=engine)
    session = Session()
    return speciesnames, seqnames, hints, featuretypes, session 
開發者ID:ComparativeGenomicsToolkit,項目名稱:Comparative-Annotation-Toolkit,代碼行數:24,代碼來源:hintsDatabaseInterface.py

示例14: five_minute_pv

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def five_minute_pv():
    db_str_target = local_history_database["db_str"]
    engine_target = create_engine(db_str_target, echo=False)
    Session_target = sessionmaker(bind=engine_target)
    session_target = Session_target()

    session_source = Session_target()

    for i in range(8760*12):

        row_source = session_source.query(one_minute_history_data.PV_PG).filter(and_(one_minute_history_data.TIME_STAMP>=i*5,one_minute_history_data.TIME_STAMP<(i+1)*5)).all()

        row = session_target.query(five_minutes_history_data).filter(five_minutes_history_data.TIME_STAMP == i).first()
        temp = 0
        for j in range(5):
            temp += row_source[j][0]

        row.PV_PG = temp/5

        session_target.commit()
        print(i) 
開發者ID:Matrixeigs,項目名稱:energy_management_system,代碼行數:23,代碼來源:histoty_data_management.py

示例15: half_hour_pv

# 需要導入模塊: from sqlalchemy import orm [as 別名]
# 或者: from sqlalchemy.orm import sessionmaker [as 別名]
def half_hour_pv():
    db_str_target = local_history_database["db_str"]
    engine_target = create_engine(db_str_target, echo=False)
    Session_target = sessionmaker(bind=engine_target)
    session_target = Session_target()

    session_source = Session_target()

    for i in range(8760*2):

        row_source = session_source.query(five_minutes_history_data.PV_PG).filter(and_(five_minutes_history_data.TIME_STAMP>=i*6,five_minutes_history_data.TIME_STAMP<(i+1)*6)).all()

        row = session_target.query(half_hourly_history_data).filter(half_hourly_history_data.TIME_STAMP == i).first()
        temp = 0
        for j in range(6):
            temp += row_source[j][0]

        row.PV_PG = temp/6

        session_target.commit()
        print(i) 
開發者ID:Matrixeigs,項目名稱:energy_management_system,代碼行數:23,代碼來源:histoty_data_management.py


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