Skip to content

Providing new database session for each request #493

Answered by hakanutku
hakanutku asked this question in Q&A
Discussion options

You must be logged in to vote

Sorry for the super late answer @SarloAkrobata, I had some really busy workdays lately. Here is the solution I found:

First, I tried to use ContextLocalSingleton as suggested by @rmk135 , but I couldn't manage to use the same session for the endpoint, dependencies and middlewares. I don't remember exactly, but I think FastAPI was executing middlewares in a separate context. My alternate solution was to create the context manually.

# database.py looks roughly like this

_request_id_ctx_var: contextvars.ContextVar[str] = contextvars.ContextVar('request_id_ctx')

def get_request_id() -> str:
    return _request_id_ctx_var.get()
    
@contextmanager
def db_context(identifier: str):
    ctx_token

Replies: 6 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by hakanutku
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@JobaDiniz
Comment options

@hakanutku
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy