本文整理汇总了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...")
示例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
示例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
示例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)
示例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()
示例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()
示例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")
示例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)
示例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
示例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)
示例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
示例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 = {}
示例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)
示例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)