本文整理汇总了Python中sqlalchemy.engine.Engine方法的典型用法代码示例。如果您正苦于以下问题:Python engine.Engine方法的具体用法?Python engine.Engine怎么用?Python engine.Engine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.engine
的用法示例。
在下文中一共展示了engine.Engine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [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
示例2: first_connect
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def first_connect(self, dbapi_connection, connection_record):
"""Called exactly once for the first time a DBAPI connection is
checked out from a particular :class:`.Pool`.
The rationale for :meth:`.PoolEvents.first_connect` is to determine
information about a particular series of database connections based
on the settings used for all connections. Since a particular
:class:`.Pool` refers to a single "creator" function (which in terms
of a :class:`.Engine` refers to the URL and connection options used),
it is typically valid to make observations about a single connection
that can be safely assumed to be valid about all subsequent
connections, such as the database version, the server and client
encoding settings, collation settings, and many others.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
示例3: set_engine_execution_options
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def set_engine_execution_options(self, engine, opts):
"""Intercept when the :meth:`.Engine.execution_options`
method is called.
The :meth:`.Engine.execution_options` method produces a shallow
copy of the :class:`.Engine` which stores the new options. That new
:class:`.Engine` is passed here. A particular application of this
method is to add a :meth:`.ConnectionEvents.engine_connect` event
handler to the given :class:`.Engine` which will perform some per-
:class:`.Connection` task specific to these execution options.
:param conn: The newly copied :class:`.Engine` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_connection_execution_options` - event
which is called when :meth:`.Connection.execution_options` is
called.
"""
示例4: engine_disposed
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def engine_disposed(self, engine):
"""Intercept when the :meth:`.Engine.dispose` method is called.
The :meth:`.Engine.dispose` method instructs the engine to
"dispose" of it's connection pool (e.g. :class:`.Pool`), and
replaces it with a new one. Disposing of the old pool has the
effect that existing checked-in connections are closed. The new
pool does not establish any new connections until it is first used.
This event can be used to indicate that resources related to the
:class:`.Engine` should also be cleaned up, keeping in mind that the
:class:`.Engine` can still be used for new requests in which case
it re-acquires connection resources.
.. versionadded:: 1.0.5
"""
示例5: run_migrations_offline
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
示例6: get_database_engine
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def get_database_engine(
config: Config, poolclass: Optional[Type[Pool]] = None,
) -> Engine:
try:
engine = config.DATABASE_ENGINE
except AttributeError:
url = config.DATABASE_URL
echo = config.DATABASE_ECHO
engine = create_database_engine(url, echo, poolclass)
else:
if engine is None:
url = config.DATABASE_URL
echo = config.DATABASE_ECHO
engine = create_database_engine(url, echo, poolclass)
return engine
示例7: execute
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def execute(self, statement, engine=None, *args, **kwargs):
"""
Executes a raw SQL statement.
.. warning::
Avoid calling this method directly if possible. Use ``insert``,
``update`` and ``delete`` methods instead if possible. Don't use this
method if you need to select records, use the ``select`` method
instead, as this method is mostly meant to execute raw SQL without
returning anything.
:param statement: SQL to be executed
:type statement: str
:param engine: Engine to be used (default: default class engine)
:type engine: str
:param args: Extra arguments that will be passed to ``sqlalchemy.create_engine`` (see http://docs.sqlalchemy.org/en/latest/core/engines.html)
:param kwargs: Extra kwargs that will be passed to ``sqlalchemy.create_engine`` (see http://docs.sqlalchemy.org/en/latest/core/engines.html)
"""
engine = self._get_engine(engine, *args, **kwargs)
with engine.connect() as connection:
result = connection.execute(statement)
示例8: __init__
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def __init__(
self,
app: ASGIApp,
db_url: Optional[Union[str, URL]] = None,
custom_engine: Optional[Engine] = None,
engine_args: Dict = None,
session_args: Dict = None,
):
super().__init__(app)
global _Session
engine_args = engine_args or {}
session_args = session_args or {}
if not custom_engine and not db_url:
raise ValueError("You need to pass a db_url or a custom_engine parameter.")
if not custom_engine:
engine = create_engine(db_url, **engine_args)
else:
engine = custom_engine
_Session = sessionmaker(bind=engine, **session_args)
示例9: with_engine
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def with_engine(f, *a, **kw):
"""Decorator for :mod:`migrate.versioning.api` functions
to safely close resources after function usage.
Passes engine parameters to :func:`construct_engine` and
resulting parameter is available as kw['engine'].
Engine is disposed after wrapped function is executed.
.. versionadded: 0.6.0
"""
url = a[0]
engine = construct_engine(url, **kw)
try:
kw['engine'] = engine
return f(*a, **kw)
finally:
if isinstance(engine, Engine) and engine is not url:
log.debug('Disposing SQLAlchemy engine %s', engine)
engine.dispose()
示例10: setup_table
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def setup_table(self, table: Any) -> None:
if self._engine is None:
raise Exception("Engine not set when required: {}".format(self))
try:
table.__table__.create(self._engine, checkfirst=True)
except InternalError as e:
if "Table '{}' already exists".format(table.__tablename__) in str(e):
# This is a race condition from checkfirst=True. Can happen
# if two threads call this method at the same time.
pass
else:
raise
示例11: _accept_with
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def _accept_with(cls, target):
if isinstance(target, type):
if issubclass(target, Engine):
return Pool
elif issubclass(target, Pool):
return target
elif isinstance(target, Engine):
return target.pool
else:
return target
示例12: before_execute
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def before_execute(self, conn, clauseelement, multiparams, params):
"""Intercept high level execute() events, receiving uncompiled
SQL constructs and other objects prior to rendering into SQL.
This event is good for debugging SQL compilation issues as well
as early manipulation of the parameters being sent to the database,
as the parameter lists will be in a consistent format here.
This event can be optionally established with the ``retval=True``
flag. The ``clauseelement``, ``multiparams``, and ``params``
arguments should be returned as a three-tuple in this case::
@event.listens_for(Engine, "before_execute", retval=True)
def before_execute(conn, conn, clauseelement, multiparams, params):
# do something with clauseelement, multiparams, params
return clauseelement, multiparams, params
:param conn: :class:`.Connection` object
:param clauseelement: SQL expression construct, :class:`.Compiled`
instance, or string statement passed to :meth:`.Connection.execute`.
:param multiparams: Multiple parameter sets, a list of dictionaries.
:param params: Single parameter set, a single dictionary.
See also:
:meth:`.before_cursor_execute`
"""
示例13: before_cursor_execute
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def before_cursor_execute(self, conn, cursor, statement,
parameters, context, executemany):
"""Intercept low-level cursor execute() events before execution,
receiving the string SQL statement and DBAPI-specific parameter list to
be invoked against a cursor.
This event is a good choice for logging as well as late modifications
to the SQL string. It's less ideal for parameter modifications except
for those which are specific to a target backend.
This event can be optionally established with the ``retval=True``
flag. The ``statement`` and ``parameters`` arguments should be
returned as a two-tuple in this case::
@event.listens_for(Engine, "before_cursor_execute", retval=True)
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
# do something with statement, parameters
return statement, parameters
See the example at :class:`.ConnectionEvents`.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object
:param statement: string SQL statement, as to be passed to the DBAPI
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param executemany: boolean, if ``True``, this is an ``executemany()``
call, if ``False``, this is an ``execute()`` call.
See also:
:meth:`.before_execute`
:meth:`.after_cursor_execute`
"""
示例14: set_connection_execution_options
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def set_connection_execution_options(self, conn, opts):
"""Intercept when the :meth:`.Connection.execution_options`
method is called.
This method is called after the new :class:`.Connection` has been
produced, with the newly updated execution options collection, but
before the :class:`.Dialect` has acted upon any of those new options.
Note that this method is not called when a new :class:`.Connection`
is produced which is inheriting execution options from its parent
:class:`.Engine`; to intercept this condition, use the
:meth:`.ConnectionEvents.engine_connect` event.
:param conn: The newly copied :class:`.Connection` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_engine_execution_options` - event
which is called when :meth:`.Engine.execution_options` is called.
"""
示例15: create_sa_connection
# 需要导入模块: from sqlalchemy import engine [as 别名]
# 或者: from sqlalchemy.engine import Engine [as 别名]
def create_sa_connection(con, **kwargs):
import sqlalchemy as sa
from sqlalchemy.engine import Connection, Engine
# process con
engine = None
if isinstance(con, Connection):
# connection create by user
close = False
dispose = False
elif isinstance(con, Engine):
con = con.connect()
close = True
dispose = False
else:
engine = sa.create_engine(con, **kwargs)
con = engine.connect()
close = True
dispose = True
try:
yield con
finally:
if close:
con.close()
if dispose:
engine.dispose()