本文整理汇总了Python中sqlalchemy.pool.StaticPool方法的典型用法代码示例。如果您正苦于以下问题:Python pool.StaticPool方法的具体用法?Python pool.StaticPool怎么用?Python pool.StaticPool使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.pool
的用法示例。
在下文中一共展示了pool.StaticPool方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_query
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def test_query():
sa_engine = create_engine(
'sqlite://',
connect_args={'check_same_thread': False},
poolclass=StaticPool,
)
setup_db(sa_engine)
app = ConsoleApplication(GRAPH, engine, {SA_ENGINE_KEY: sa_engine},
debug=True)
query = b'[{:bar_list [:name :type {:foo_s [:name :count]}]}]'
status, headers, content = request(app, 'POST', '/', payload=query)
assert status == '200 OK'
assert ('Content-Type', 'application/json') in headers
result = json.loads(content.decode('utf-8'))
assert 'bar_list' in result
示例2: setup_connection
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def setup_connection(self) -> None:
assert isinstance(self.settings, SQLAlchemySettings), self.settings
if self._engine is None:
# Create SQLAlchemy engine.
if self.is_sqlite():
kwargs: Dict[str, Any] = {"connect_args": {"check_same_thread": False}}
elif self.settings.pool_size == 1:
kwargs = {"poolclass": StaticPool}
else:
kwargs = {"pool_size": self.settings.pool_size}
self._engine = create_engine(
self.settings.uri,
strategy=self._connection_strategy,
# echo=True,
**kwargs
)
assert self._engine
示例3: get_engine
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def get_engine(path=None, dialect="sqlite", echo=False):
if path is None:
# In memory database
url = "sqlite://"
elif dialect == "sqlite":
url = "%s:///%s" % (dialect, path)
if url in engines and os.path.isfile(path) and os.path.getsize(path) > 0:
return engines[url]
else:
if path is None:
engine = create_engine(url, connect_args={'check_same_thread': False},
echo=echo, poolclass=StaticPool)
else:
if path != empty_db and (not os.path.isfile(path) or os.path.getsize(path) == 0):
shutil.copyfile(empty_db, path)
engine = create_engine(url, echo=echo)
if path != empty_db and (path is None or get_schema_version(engine) != SCHEMA_VERSION):
metadata.drop_all(engine)
metadata.create_all(engine)
ini_schema_version(engine)
engines[url] = engine
return engine
示例4: test_no_connect_on_recreate
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def test_no_connect_on_recreate(self):
def creator():
raise Exception("no creates allowed")
for cls in (
pool.SingletonThreadPool,
pool.StaticPool,
pool.QueuePool,
pool.NullPool,
pool.AssertionPool,
):
p = cls(creator=creator)
p.dispose()
p2 = p.recreate()
assert p2.__class__ is cls
mock_dbapi = MockDBAPI()
p = cls(creator=mock_dbapi.connect)
conn = p.connect()
conn.close()
mock_dbapi.connect.side_effect = Exception("error!")
p.dispose()
p.recreate()
示例5: check
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def check(self, src, value):
sa_engine = create_engine(
'sqlite://',
connect_args={'check_same_thread': False},
poolclass=StaticPool,
)
setup_db(sa_engine)
engine = Engine(ThreadsExecutor(thread_pool))
result = engine.execute(self.graph, read(src),
{SA_ENGINE_KEY: sa_engine})
check_result(result, value)
示例6: setup_bind
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def setup_bind(cls):
if config.requirements.independent_connections.enabled:
from sqlalchemy import pool
return engines.testing_engine(
options=dict(poolclass=pool.StaticPool))
else:
return config.db
示例7: __init__
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def __init__(self, serializer):
self.serializer = serializer
self.connection_string = 'postgresql://%s:%s@%s/%s' % (
settings.POSTGRES_USERNAME,
settings.POSTGRES_PASSWORD,
settings.POSTGRES_HOST,
settings.POSTGRES_DATABASE)
self.engine = create_engine(self.connection_string, poolclass=StaticPool)
self.Session = sessionmaker(bind=self.engine)
示例8: __init__
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def __init__(self, *args, **kwargs):
super().__init__()
args = list(args)
if args[0].endswith(":memory:"):
args[0] = args[0].replace(":memory:", "")
if args[0] == "sqlite://": # in-memory
kwargs.update({
"connect_args": {'check_same_thread': False},
"poolclass": StaticPool,
})
self.engine = create_engine(*args, **kwargs)
self.session = sessionmaker(bind=self.engine)()
else:
self.engine = create_engine(*args, **kwargs)
self.session = scoped_session(sessionmaker(bind=self.engine))
示例9: _init_connection_args
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def _init_connection_args(url, engine_args, **kw):
pool_class = url.get_dialect().get_pool_class(url)
# singletonthreadpool is used for :memory: connections;
# replace it with StaticPool.
if issubclass(pool_class, pool.SingletonThreadPool):
engine_args["poolclass"] = pool.StaticPool
engine_args['connect_args']['check_same_thread'] = False
示例10: setup_database
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def setup_database(dburl, echo, num):
global engine
engine = create_engine(dburl, echo=echo)
if engine.dialect.name == "sqlite":
engine.pool = pool.StaticPool(creator=engine.pool._creator)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
示例11: setup_bind
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def setup_bind(cls):
if config.requirements.independent_connections.enabled:
from sqlalchemy import pool
return engines.testing_engine(
options=dict(poolclass=pool.StaticPool)
)
else:
return config.db
示例12: test_static_pool
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def test_static_pool(self):
self._do_test(pool.StaticPool, ["R", "R"])
示例13: test_recreate
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def test_recreate(self):
dbapi = MockDBAPI()
def creator():
return dbapi.connect("foo.db")
p = pool.StaticPool(creator)
p2 = p.recreate()
assert p._creator is p2._creator
示例14: reset_filesystem
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def reset_filesystem(self, users=(), applications=()):
"""
Create in-memory DB that can be accessed by multiple threads.
Set up auth requests, the rate limit bucket, and the request log.
"""
self._db_engine = sqlalchemy.create_engine(
'sqlite:///:memory:',
connect_args={'check_same_thread': False},
poolclass=StaticPool,
)
DbModel.metadata.create_all(self._db_engine)
self._db_session_maker = sessionmaker(bind=self._db_engine, autoflush=True)
self._db_session = self._db_session_maker()
self._db_session.add(FolderModel(folder_id=0))
self._db_session.commit()
self._rate_limit_bucket = (self.RATE_LIMIT_THRESHOLD, datetime.utcnow())
self._request_log = []
self._oauth_behavior = OAuth2Behavior(self._db_session)
self._file_behavior = FileBehavior(self._db_session)
self._folder_behavior = FolderBehavior(self._db_session)
self._event_behavior = EventBehavior(self._db_session)
self._user_behavior = UserBehavior(self._db_session)
user_ids = []
for user_info in users:
user_name, user_login = user_info
user_id = self.add_user(user_name, user_login)
user_ids.append(user_id)
for app_info in applications:
client_id, client_secret, user_index = app_info
self.add_application(client_id, client_secret, user_ids[user_index])
示例15: construct_engine
# 需要导入模块: from sqlalchemy import pool [as 别名]
# 或者: from sqlalchemy.pool import StaticPool [as 别名]
def construct_engine(engine, **opts):
""".. versionadded:: 0.5.4
Constructs and returns SQLAlchemy engine.
Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions:
:param engine: connection string or a existing engine
:param engine_dict: python dictionary of options to pass to `create_engine`
:param engine_arg_*: keyword parameters to pass to `create_engine` (evaluated with :func:`migrate.versioning.util.guess_obj_type`)
:type engine_dict: dict
:type engine: string or Engine instance
:type engine_arg_*: string
:returns: SQLAlchemy Engine
.. note::
keyword parameters override ``engine_dict`` values.
"""
if isinstance(engine, Engine):
return engine
elif not isinstance(engine, six.string_types):
raise ValueError("you need to pass either an existing engine or a database uri")
# get options for create_engine
if opts.get('engine_dict') and isinstance(opts['engine_dict'], dict):
kwargs = opts['engine_dict']
else:
kwargs = dict()
# DEPRECATED: handle echo the old way
echo = asbool(opts.get('echo', False))
if echo:
warnings.warn('echo=True parameter is deprecated, pass '
'engine_arg_echo=True or engine_dict={"echo": True}',
exceptions.MigrateDeprecationWarning)
kwargs['echo'] = echo
# parse keyword arguments
for key, value in six.iteritems(opts):
if key.startswith('engine_arg_'):
kwargs[key[11:]] = guess_obj_type(value)
log.debug('Constructing engine')
# TODO: return create_engine(engine, poolclass=StaticPool, **kwargs)
# seems like 0.5.x branch does not work with engine.dispose and staticpool
return create_engine(engine, **kwargs)