本文整理汇总了Python中sqlalchemy.event.listen方法的典型用法代码示例。如果您正苦于以下问题:Python event.listen方法的具体用法?Python event.listen怎么用?Python event.listen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.event
的用法示例。
在下文中一共展示了event.listen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: define_views
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def define_views(cls, metadata, schema):
for table_name in ('users', 'email_addresses'):
fullname = table_name
if schema:
fullname = "%s.%s" % (schema, table_name)
view_name = fullname + '_v'
query = "CREATE VIEW %s AS SELECT * FROM %s" % (
view_name, fullname)
event.listen(
metadata,
"after_create",
DDL(query)
)
event.listen(
metadata,
"before_drop",
DDL("DROP VIEW %s" % view_name)
)
示例2: _listen
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def _listen(cls, event_key, raw=False, propagate=False, **kw):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, event_key.fn
if target.class_ in target.all_holds:
collection = target.all_holds[target.class_]
else:
collection = target.all_holds[target.class_] = {}
event.registry._stored_in_collection(event_key, target)
collection[event_key._key] = (event_key, raw, propagate)
if propagate:
stack = list(target.class_.__subclasses__())
while stack:
subclass = stack.pop(0)
stack.extend(subclass.__subclasses__())
subject = target.resolve(subclass)
if subject is not None:
# we are already going through __subclasses__()
# so leave generic propagate flag False
event_key.with_dispatch_target(subject).\
listen(raw=raw, propagate=False, **kw)
示例3: __init__
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def __init__(self, field, allow_null, throw_exception, message,
interpolate_message, parent):
""" Initialize a Validator object.
:type throw_exception: Throw a ValidateError exception
:param field: Model.field | Column to listen
:param interpolate_message: Validator interpolates message with
values from context if True, outputs original message otherwise
"""
self.parent = weakref.ref(parent)
self.field = field
self.allow_null = allow_null
self.throw_exception = throw_exception
self.message = message
self.interpolate_message = interpolate_message
self.__create_event()
示例4: _listen
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def _listen(cls, event_key, propagate=True, **kw):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, \
event_key._listen_fn
def listen(target_cls, *arg):
listen_cls = target()
if propagate and issubclass(target_cls, listen_cls):
return fn(target_cls, *arg)
elif not propagate and target_cls is listen_cls:
return fn(target_cls, *arg)
def remove(ref):
key = event.registry._EventKey(
None, identifier, listen,
instrumentation._instrumentation_factory)
getattr(instrumentation._instrumentation_factory.dispatch,
identifier).remove(key)
target = weakref.ref(target.class_, remove)
event_key.\
with_dispatch_target(instrumentation._instrumentation_factory).\
with_wrapper(listen).base_listen(**kw)
示例5: associate_with
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def associate_with(cls, sqltype):
"""Associate this wrapper with all future mapped columns
of the given type.
This is a convenience method that calls
``associate_with_attribute`` automatically.
.. warning::
The listeners established by this method are *global*
to all mappers, and are *not* garbage collected. Only use
:meth:`.associate_with` for types that are permanent to an
application, not with ad-hoc types else this will cause unbounded
growth in memory usage.
"""
def listen_for_type(mapper, class_):
for prop in mapper.column_attrs:
if isinstance(prop.columns[0].type, sqltype):
cls.associate_with_attribute(getattr(class_, prop.key))
event.listen(mapper, 'mapper_configured', listen_for_type)
示例6: listens_for
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def listens_for(target, identifier, *args, **kw):
"""Decorate a function as a listener for the given target + identifier.
e.g.::
from sqlalchemy import event
from sqlalchemy.schema import UniqueConstraint
@event.listens_for(UniqueConstraint, "after_parent_attach")
def unique_constraint_name(const, table):
const.name = "uq_%s_%s" % (
table.name,
list(const.columns)[0].name
)
A given function can also be invoked for only the first invocation
of the event using the ``once`` argument::
@event.listens_for(Mapper, "before_configure", once=True)
def on_config():
do_config()
.. versionadded:: 0.9.4 Added ``once=True`` to :func:`.event.listen`
and :func:`.event.listens_for`.
.. seealso::
:func:`.listen` - general description of event listening
"""
def decorate(fn):
listen(target, identifier, fn, *args, **kw)
return fn
return decorate
示例7: contains
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def contains(target, identifier, fn):
"""Return True if the given target/ident/fn is set up to listen.
.. versionadded:: 0.9.0
"""
return _event_key(target, identifier, fn).contains()
示例8: execute_at
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def execute_at(self, event_name, target):
"""Link execution of this DDL to the DDL lifecycle of a SchemaItem.
Links this ``DDLElement`` to a ``Table`` or ``MetaData`` instance,
executing it when that schema item is created or dropped. The DDL
statement will be executed using the same Connection and transactional
context as the Table create/drop itself. The ``.bind`` property of
this statement is ignored.
:param event:
One of the events defined in the schema item's ``.ddl_events``;
e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop'
:param target:
The Table or MetaData instance for which this DDLElement will
be associated with.
A DDLElement instance can be linked to any number of schema items.
``execute_at`` builds on the ``append_ddl_listener`` interface of
:class:`.MetaData` and :class:`.Table` objects.
Caveat: Creating or dropping a Table in isolation will also trigger
any DDL set to ``execute_at`` that Table's MetaData. This may change
in a future release.
"""
def call_event(target, connection, **kw):
if self._should_execute_deprecated(event_name,
target, connection, **kw):
return connection.execute(self.against(target))
event.listen(target, "" + event_name.replace('-', '_'), call_event)
示例9: define_temp_tables
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def define_temp_tables(cls, metadata):
# cheat a bit, we should fix this with some dialect-level
# temp table fixture
if testing.against("oracle"):
kw = {
'prefixes': ["GLOBAL TEMPORARY"],
'oracle_on_commit': 'PRESERVE ROWS'
}
else:
kw = {
'prefixes': ["TEMPORARY"],
}
user_tmp = Table(
"user_tmp", metadata,
Column("id", sa.INT, primary_key=True),
Column('name', sa.VARCHAR(50)),
Column('foo', sa.INT),
sa.UniqueConstraint('name', name='user_tmp_uq'),
sa.Index("user_tmp_ix", "foo"),
**kw
)
if testing.requires.view_reflection.enabled and \
testing.requires.temporary_views.enabled:
event.listen(
user_tmp, "after_create",
DDL("create temporary view user_tmp_v as "
"select * from user_tmp")
)
event.listen(
user_tmp, "before_drop",
DDL("drop view user_tmp_v")
)
示例10: populate
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def populate(cls, class_, subject):
for subclass in class_.__mro__:
if subclass in cls.all_holds:
collection = cls.all_holds[subclass]
for event_key, raw, propagate in collection.values():
if propagate or subclass is class_:
# since we can't be sure in what order different
# classes in a hierarchy are triggered with
# populate(), we rely upon _EventsHold for all event
# assignment, instead of using the generic propagate
# flag.
event_key.with_dispatch_target(subject).\
listen(raw=raw, propagate=False)
示例11: before_parent_attach
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def before_parent_attach(self, target, parent):
"""Called before a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
示例12: after_parent_attach
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def after_parent_attach(self, target, parent):
"""Called after a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
示例13: register
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def register(cls, session):
if not hasattr(session, '_model_changes'):
session._model_changes = {}
event.listen(session, 'before_flush', cls.record_ops)
event.listen(session, 'before_commit', cls.record_ops)
event.listen(session, 'before_commit', cls.before_commit)
event.listen(session, 'after_commit', cls.after_commit)
event.listen(session, 'after_rollback', cls.after_rollback)
示例14: get_engine
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def get_engine(echo=True):
""" Creates a engine to a specific database.
:returns: engine
"""
global _ENGINE
if not _ENGINE:
sql_connection = config_get(DATABASE_SECTION, 'default')
config_params = [('pool_size', int), ('max_overflow', int), ('pool_timeout', int),
('pool_recycle', int), ('echo', int), ('echo_pool', str),
('pool_reset_on_return', str), ('use_threadlocal', int)]
params = {}
if 'mysql' in sql_connection:
conv = mysql_convert_decimal_to_float()
params['connect_args'] = {'conv': conv}
for param, param_type in config_params:
try:
params[param] = param_type(config_get(DATABASE_SECTION, param))
except:
pass
_ENGINE = create_engine(sql_connection, **params)
if 'mysql' in sql_connection:
event.listen(_ENGINE, 'checkout', mysql_ping_listener)
elif 'postgresql' in sql_connection:
event.listen(_ENGINE, 'connect', psql_convert_decimal_to_float)
elif 'sqlite' in sql_connection:
event.listen(_ENGINE, 'connect', _fk_pragma_on_connect)
elif 'oracle' in sql_connection:
event.listen(_ENGINE, 'connect', my_on_connect)
assert _ENGINE
return _ENGINE
示例15: define_temp_tables
# 需要导入模块: from sqlalchemy import event [as 别名]
# 或者: from sqlalchemy.event import listen [as 别名]
def define_temp_tables(cls, metadata):
# the definition of temporary tables in the temporary table tests needs to be overwritten,
# because similar to oracle, in HANA one needs to mention GLOBAL or LOCAL in the temporary table definition
if testing.against("hana"):
kw = {
'prefixes': ["GLOBAL TEMPORARY"],
}
else:
kw = {
'prefixes': ["TEMPORARY"],
}
user_tmp = Table(
"user_tmp", metadata,
Column("id", sa.INT, primary_key=True),
Column('name', sa.VARCHAR(50)),
Column('foo', sa.INT),
sa.UniqueConstraint('name', name='user_tmp_uq'),
sa.Index("user_tmp_ix", "foo"),
**kw
)
if testing.requires.view_reflection.enabled and \
testing.requires.temporary_views.enabled:
event.listen(
user_tmp, "after_create",
DDL("create temporary view user_tmp_v as "
"select * from user_tmp")
)
event.listen(
user_tmp, "before_drop",
DDL("drop view user_tmp_v")
)