r/FastAPI • u/bluewalt • Aug 31 '24
Question Equivalent of Django commands in FastAPI?
Hi there, I'm trying to set up in fastAPI the (more or less) equivalent of Django Commands. These are scripts that are context-aware (you can use database, settings, etc). They can have doc, and they write logs using the default config.
For now, my current set up is a back/app/scripts/seed_db.py for example, for a script to put initial fake data in db:. It looks like this:
=
return
# Fill fake data here thanks to session being accessible
"""Run: `python -m back.app.scripts.seed_db` from the root folder """
It kind of works but seems suboptimal to me, for at least these reasons:
- I have to configure logging again (it's not centralized)
- As I'm loading my settings via pydantic_settings using
model_config = SettingsConfigDict(env_file=".env"), it seems that I need to be at the root of my project to run my script usingpython -m back.app.scripts.seed_db, otherwise.envfile can't be found. - The injectable dependencies I built for the project, like
get_sessionseems to not work with an external script.
In the end, I'm wondering if these problems can be fixed easily, or if there is a better way to handle "commands" (external scripts) in fastAPI.
Thanks.
View all comments
Show parent comment
1
u/bluewalt Aug 31 '24
Thanks a lot for these good points. I extracted my custom logger in a file (I was hopping to use the exact same than FastAPI CLI, but I guess it's not that important).
I used absolute path for
env_fileand it works better:I still have the "ImportError: attempted relative import with no known parent package" because I'm using relative imports like:
from ..core.config import get_settingsin my script.When I change this to
from app.core.config import get_settings, I got aModuleNotFoundError: No module named 'app'. I guess I should somehow add thisappfolder to the python PATH?About Typer, I'm not sure of what it would bring to me compared to a raw script (except command parameters parsing)?
Thanks!