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