-
Hi, I was wondering what the best way is to get a db session outside of a route handler. I know that with the If I am using a security backend like the session backend, I might want to get the Before, I would just create a session maker from One solution would be to change that and ensure that the global reference is always correctly configured. However, I think the safer way is to instead have the app instance (e.g., as set up by the test client) provide the session maker. I produced something like this but it is not working, e.g. when using it in the What am I doing wrong? Is the connection state not yet fully populated when the Snippet below for example usage. async def session_maker(connection: ASGIConnection) -> AsyncSession:
"""Fetch a session for the current connection."""
session_provider = connection.app.dependencies.get("db_session")
session = await session_provider(state=connection.state, scope=connection.scope)
return session
...
async def retrieve_user_handler(session: dict[str, Any], connection: ASGIConnection) -> User:
"""Fetches the current user state from the database and returns it as User instance."""
db_session: AsyncSession = await session_maker(connection)
user_id = session.get(SESSION_USER_ID_KEY)
async with db_session.begin():
user = await db_session.get(
entity=User,
ident=(user_id,),
)
... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Can you try |
Beta Was this translation helpful? Give feedback.
-
I have a follow-up question on this.. as this workaround might occasionally break later use of the session in this request. I'm still learning about the details of async sqlalchemy so maybe there is a simple way of solving this that I am not aware of. I use the approach above to provide a session from a connection to functions that do not have access to dependency injection like the async def retrieve_user_handler(session: dict[str, Any], connection: ASGIConnection) -> User | Admin:
"""Fetches the current user state from the database and returns it as User instance."""
db_session: AsyncSession = await session_maker(connection)
user_id = session.get(SESSION_USER_ID_KEY)
async with db_session.begin():
user = await db_session.get(
entity=User,
ident=(user_id,),
options=(selectinload(User.projects),)
)
if user is None:
raise exceptions.HTTPException(status_code=status_codes.HTTP_400_BAD_REQUEST, detail="User not found.")
db_session.expunge(user)
return user Now, for some route handlers where I do similar
And I dont get it: The primary object I'm querying is still returned correctly, but any relationship objects are not. At one point I also got the message that the "current session was already used", so I'm wondering if the error actually comes from my |
Beta Was this translation helpful? Give feedback.
Can you try
session = await session_provider(state=connection.scope['app'].state, scope=connection.scope)