def __init__(self, session_factory, scopefunc=None): self.session_factory = session_factory if scopefunc: self.registry = ScopedRegistry(session_factory, scopefunc) else: self.registry = ThreadLocalRegistry(session_factory) self.extension = _ScopedExt(self)
def Configure(cls, app, engine, monkey_patch_debugtoolbar=True, package_names=None): """Configure the debug panel with an engine and session :param Flask app: flask application :param Engine engine: sqlalchemy Engine :param callable session: callable that returns a :param monkey_patch_debugtoolbar: replace existing SQLalchemy debug panel (default True) """ if monkey_patch_debugtoolbar: _monkey_patch_flasksqlalchemy_panel() if package_names: cls.package_names = package_names else: cls.package_names = [] cls._engine = engine scopefunc = _app_ctx_stack.__ident_func__ cls._locals = ScopedRegistry(dict, scopefunc) @app.teardown_request def clear_statements(*args, **kwargs): cls._locals.clear() event.listen(cls._engine, "before_cursor_execute", cls._before_cursor_execute) event.listen(cls._engine, "after_cursor_execute", cls._after_cursor_execute)
def init(connection_uri, echo=False, scopefunc=None): """Initialize the session. Args: connection_uri (str): The connection uri, such as "postgrseql://*****:*****@localhost/dbname" echo (bool): Echo SQL statements to stdout. Useful for debugging. scopefunc (func): Optional function which defines the current scope. See http://docs.sqlalchemy.org/en/latest/orm/contextual.html#sqlalchemy.orm.scoping.scoped_session.__init__ for more information. If this is not passed, the "thread-local" scope will be assumed. """ global engine, session from frf.models import Model if 'postgres' in connection_uri: engine = create_engine(connection_uri, echo=echo, json_serializer=serialize, json_deserializer=deserialize) else: engine = create_engine(connection_uri, echo=echo) if scopefunc is not None: session.registry = ScopedRegistry(session.session_factory, scopefunc=scopefunc) else: session.registry = ThreadLocalRegistry(session.session_factory) session.configure(bind=engine) Model.query = _QueryProperty(session)
def __init__(self, session_factory, scopefunc=None): # pylint: disable=super-init-not-called self.session_factory = session_factory if scopefunc: self.registry = ScopedRegistry(session_factory, scopefunc) else: self.registry = FalconOauthRegistry(session_factory)
class SessionContext(object): """A simple wrapper for ScopedRegistry that provides a "current" property which can be used to get, set, or remove the session in the current scope. By default this object provides thread-local scoping, which is the default scope provided by sqlalchemy.util.ScopedRegistry. Usage: engine = create_engine(...) def session_factory(): return Session(bind_to=engine) context = SessionContext(session_factory) s = context.current # get thread-local session context.current = Session(bind_to=other_engine) # set current session del context.current # discard the thread-local session (a new one will # be created on the next call to context.current) """ def __init__(self, session_factory, scopefunc=None): self.registry = ScopedRegistry(session_factory, scopefunc) super(SessionContext, self).__init__() def get_current(self): return self.registry() def set_current(self, session): self.registry.set(session) def del_current(self): self.registry.clear() current = property( get_current, set_current, del_current, """Property used to get/set/del the session in the current scope""") def _get_mapper_extension(self): try: return self._extension except AttributeError: self._extension = ext = SessionContextExt(self) return ext mapper_extension = property( _get_mapper_extension, doc= """get a mapper extension that implements get_session using this context""" )
class SessionContext(object): """A simple wrapper for ``ScopedRegistry`` that provides a `current` property which can be used to get, set, or remove the session in the current scope. By default this object provides thread-local scoping, which is the default scope provided by sqlalchemy.util.ScopedRegistry. Usage:: engine = create_engine(...) def session_factory(): return Session(bind_to=engine) context = SessionContext(session_factory) s = context.current # get thread-local session context.current = Session(bind_to=other_engine) # set current session del context.current # discard the thread-local session (a new one will # be created on the next call to context.current) """ def __init__(self, session_factory, scopefunc=None): self.registry = ScopedRegistry(session_factory, scopefunc) super(SessionContext, self).__init__() def get_current(self): return self.registry() def set_current(self, session): self.registry.set(session) def del_current(self): self.registry.clear() current = property(get_current, set_current, del_current, """Property used to get/set/del the session in the current scope.""") def _get_mapper_extension(self): try: return self._extension except AttributeError: self._extension = ext = SessionContextExt(self) return ext mapper_extension = property(_get_mapper_extension, doc="""Get a mapper extension that implements `get_session` using this context.""")
def __init__(self, session_factory, scopefunc=None): """Construct a new :class:`.scoped_session`. :param session_factory: a factory to create new :class:`.Session` instances. This is usually, but not necessarily, an instance of :class:`.sessionmaker`. :param scopefunc: optional function which defines the current scope. If not passed, the :class:`.scoped_session` object assumes "thread-local" scope, and will use a Python ``threading.local()`` in order to maintain the current :class:`.Session`. If passed, the function should return a hashable token; this token will be used as the key in a dictionary in order to store and retrieve the current :class:`.Session`. """ self.session_factory = session_factory if scopefunc: self.registry = ScopedRegistry(session_factory, scopefunc) else: self.registry = ThreadLocalRegistry(session_factory)
class ScopedSession(object): """Provides thread-local management of Sessions. Usage:: Session = scoped_session(sessionmaker(autoflush=True)) To map classes so that new instances are saved in the current Session automatically, as well as to provide session-aware class attributes such as "query": mapper = Session.mapper mapper(Class, table, ...) """ def __init__(self, session_factory, scopefunc=None): self.session_factory = session_factory self.registry = ScopedRegistry(session_factory, scopefunc) self.extension = _ScopedExt(self) def __call__(self, **kwargs): if kwargs: scope = kwargs.pop("scope", False) if scope is not None: if self.registry.has(): raise exceptions.InvalidRequestError( "Scoped session is already present; no new arguments may be specified." ) else: sess = self.session_factory(**kwargs) self.registry.set(sess) return sess else: return self.session_factory(**kwargs) else: return self.registry() def remove(self): if self.registry.has(): self.registry().close() self.registry.clear() def mapper(self, *args, **kwargs): """return a mapper() function which associates this ScopedSession with the Mapper.""" from sqlalchemy.orm import mapper extension_args = dict([(arg, kwargs.pop(arg)) for arg in get_cls_kwargs(_ScopedExt) if arg in kwargs]) kwargs["extension"] = extension = to_list(kwargs.get("extension", [])) if extension_args: extension.append(self.extension.configure(**extension_args)) else: extension.append(self.extension) return mapper(*args, **kwargs) def configure(self, **kwargs): """reconfigure the sessionmaker used by this ScopedSession.""" self.session_factory.configure(**kwargs) def query_property(self): """return a class property which produces a `Query` object against the class when called. e.g.:: Session = scoped_session(sessionmaker()) class MyClass(object): query = Session.query_property() # after mappers are defined result = MyClass.query.filter(MyClass.name=='foo').all() """ class query(object): def __get__(s, instance, owner): mapper = class_mapper(owner, raiseerror=False) if mapper: return self.registry().query(mapper) else: return None return query()
def __init__(self, session_factory, scopefunc=None): self.session_factory = session_factory self.registry = ScopedRegistry(session_factory, scopefunc) self.extension = _ScopedExt(self)
class ScopedSession(object): """Provides thread-local management of Sessions. Usage:: Session = scoped_session(sessionmaker(autoflush=True)) To map classes so that new instances are saved in the current Session automatically, as well as to provide session-aware class attributes such as "query": mapper = Session.mapper mapper(Class, table, ...) """ def __init__(self, session_factory, scopefunc=None): self.session_factory = session_factory self.registry = ScopedRegistry(session_factory, scopefunc) self.extension = _ScopedExt(self) def __call__(self, **kwargs): if kwargs: scope = kwargs.pop('scope', False) if scope is not None: if self.registry.has(): raise exceptions.InvalidRequestError( "Scoped session is already present; no new arguments may be specified." ) else: sess = self.session_factory(**kwargs) self.registry.set(sess) return sess else: return self.session_factory(**kwargs) else: return self.registry() def remove(self): if self.registry.has(): self.registry().close() self.registry.clear() def mapper(self, *args, **kwargs): """return a mapper() function which associates this ScopedSession with the Mapper.""" from sqlalchemy.orm import mapper extension_args = dict([(arg, kwargs.pop(arg)) for arg in get_cls_kwargs(_ScopedExt) if arg in kwargs]) kwargs['extension'] = extension = to_list(kwargs.get('extension', [])) if extension_args: extension.append(self.extension.configure(**extension_args)) else: extension.append(self.extension) return mapper(*args, **kwargs) def configure(self, **kwargs): """reconfigure the sessionmaker used by this ScopedSession.""" self.session_factory.configure(**kwargs) def query_property(self): """return a class property which produces a `Query` object against the class when called. e.g.:: Session = scoped_session(sessionmaker()) class MyClass(object): query = Session.query_property() # after mappers are defined result = MyClass.query.filter(MyClass.name=='foo').all() """ class query(object): def __get__(s, instance, owner): mapper = class_mapper(owner, raiseerror=False) if mapper: return self.registry().query(mapper) else: return None return query()
class ScopedSession(object): """Provides thread-local management of Sessions. Usage:: Session = scoped_session(sessionmaker(autoflush=True)) ... use session normally. """ def __init__(self, session_factory, scopefunc=None): self.session_factory = session_factory self.registry = ScopedRegistry(session_factory, scopefunc) self.extension = _ScopedExt(self) def __call__(self, **kwargs): if kwargs: scope = kwargs.pop('scope', False) if scope is not None: if self.registry.has(): raise sa_exc.InvalidRequestError("Scoped session is already present; no new arguments may be specified.") else: sess = self.session_factory(**kwargs) self.registry.set(sess) return sess else: return self.session_factory(**kwargs) else: return self.registry() def remove(self): if self.registry.has(): self.registry().close() self.registry.clear() @deprecated("Session.mapper is deprecated. " "Please see http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper " "for information on how to replicate its behavior.") def mapper(self, *args, **kwargs): """return a mapper() function which associates this ScopedSession with the Mapper. DEPRECATED. """ from sqlalchemy.orm import mapper extension_args = dict((arg, kwargs.pop(arg)) for arg in get_cls_kwargs(_ScopedExt) if arg in kwargs) kwargs['extension'] = extension = to_list(kwargs.get('extension', [])) if extension_args: extension.append(self.extension.configure(**extension_args)) else: extension.append(self.extension) return mapper(*args, **kwargs) def configure(self, **kwargs): """reconfigure the sessionmaker used by this ScopedSession.""" self.session_factory.configure(**kwargs) def query_property(self, query_cls=None): """return a class property which produces a `Query` object against the class when called. e.g.:: Session = scoped_session(sessionmaker()) class MyClass(object): query = Session.query_property() # after mappers are defined result = MyClass.query.filter(MyClass.name=='foo').all() Produces instances of the session's configured query class by default. To override and use a custom implementation, provide a ``query_cls`` callable. The callable will be invoked with the class's mapper as a positional argument and a session keyword argument. There is no limit to the number of query properties placed on a class. """ class query(object): def __get__(s, instance, owner): try: mapper = class_mapper(owner) if mapper: if query_cls: # custom query class return query_cls(mapper, session=self.registry()) else: # session's configured query class return self.registry().query(mapper) except orm_exc.UnmappedClassError: return None return query()
def __init__(self, session_factory, scopefunc=None): self.registry = ScopedRegistry(session_factory, scopefunc) super(SessionContext, self).__init__()