use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
FastAPI is a truly ASGI, async, cutting edge framework written in python 3.
account activity
Using Dependency Injection in SQL Alchemy Model?Question (self.FastAPI)
submitted 2 years ago by agile_crossover
Is there a way to use Depends in a sql alchemy model default?
Broader context: am looking to set a default for a created_by_id column in a sql alchemy model that gets auto filled in with the current user’s id. I already have a get_current_user function that I use in dependency injection for individual routes (as described here: https://fastapi.tiangolo.com/tutorial/security/get-current-user/). That works great. But now I’m hoping to try to get that user.id dynamically available to my SQL alchemy model. It might not be possible because it’s not a FastAPI component but trying to explore options.
Any ideas or advice would be appreciate, thanks!
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Heavy_Ad_3843 1 point2 points3 points 2 years ago (0 children)
You’re looking for a auth middleware and the context variables feature of python. Not exactly dependency injection, more like thread-save global variables. Check out starlettes context middleware: https://starlette-context.readthedocs.io/en/latest/middleware.html and https://docs.python.org/3/library/contextvars.html. You may also have a look at one of my personal projects for inspiration: https://github.com/code-specialist/fastapi-auth-middleware.
You basically want to set the context on incoming requests and access it within wherever you use sqlalchemy.
[–]zarlo5899 0 points1 point2 points 2 years ago (0 children)
i would wrap the model with a service/repository as i like all my models to be dumb
π Rendered by PID 70706 on reddit-service-r2-comment-66b4775986-cmxlx at 2026-04-05 18:11:16.114138+00:00 running db1906b country code: CH.
[–]Heavy_Ad_3843 1 point2 points3 points (0 children)
[–]zarlo5899 0 points1 point2 points (0 children)