Async connection created callback #322
Unanswered
alicederyn
asked this question in
Q&A
Replies: 1 comment
-
For reference, here is my subclass implementation: from databases.core import Connection as BasicConnection, Database as BasicDatabase
class Connection(BasicConnection):
def __init__(self, backend, init_fns) -> None:
super().__init__(backend)
self.init_fns = init_fns
async def __aenter__(self):
c = await super().__aenter__()
for init_fn in self.init_fns:
await init_fn(c)
return c
class Database(BasicDatabase):
"""Adds a connection_created decorator to encode/databases."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_fns = []
def connection_created(self, async_callback_fn):
self._init_fns.append(async_callback_fn)
def connection(self):
"""This method copies the underlying implementation wholesale. Calling it with super is
unfortunately not an option as it has a hard-coded reference to its own Connection
implementation."""
if self._global_connection is not None:
return self._global_connection
try:
return self._connection_context.get()
except LookupError:
connection = Connection(self._backend, self._init_fns)
self._connection_context.set(connection)
return connection |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I need to issue a set of SQL commands at the start of each connection, e.g. to set up the search path. Currently it looks like this can only be done by subclassing
Database
and completely reimplementing itsconnection
method to return a subclass ofConnection
that overrides__aenter__
. Would it be acceptable to add something akin to Django's connection_created signal? Syntax might look likeBeta Was this translation helpful? Give feedback.
All reactions