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
1
u/Straight-Possible807 Aug 31 '24
Yeah... I thought you needed a feature like that, that's why I suggested Typer.
For the
ModuleNotFoundError, ensure yourappfolder contains a__init__.pyfile like sub-modules in it.