Each Answer to this Q is separated by one/two green lines.
The problems that I want to solve:
- Good names of directories so that their purpose is clear.
- Keeping all project files (including virtualenv) in one place, so I
can easily copy, move, archive, remove the whole project, or estimate disk
- Creating multiple copies of some selected file sets such as entire
application, repository, or virtualenv, while keeping a single copy of
other files that I don’t want to clone.
- Deploying the right set of files to the server simply by rsyncing
selected one dir.
- handling both frontend and backend nicely.
Harsha already mentioned my project generator but I think it can be helpful for future readers to explain the ideas behind of it.
When it comes to structuring the backend, if you want to render templates with Jinja, you can have something that is close to MVC Pattern.
your_project ??? __init__.py ??? main.py ??? core ? ??? models ? ? ??? database.py ? ? ??? __init__.py ? ??? schemas ? ? ??? __init__.py ? ? ??? schema.py ? ??? settings.py ??? tests ? ??? __init__.py ? ??? v1 ? ??? __init__.py ? ??? test_v1.py ??? v1 ??? api.py ??? endpoints ? ??? endpoint.py ? ??? __init__.py ??? __init__.py
__init__ everywhere, we can access the variables from the all over the app, just like Django.
Let’s the folders into parts:
- views (Add this if you are going to render templates)
It is for your database models, by doing this you can import the same database session or object from v1 and v2.
Schemas are your Pydantic models, we call it schemas because it is actually used for creating OpenAPI schemas since FastAPI is based on OpenAPI specification we use schemas everywhere, from Swagger generation to endpoint’s expected request body.
It is for Pydantic’s Settings Management which is extremely useful, you can use the same variables without redeclaring it, to see how it could be useful for you check out our documentation for Settings and Environment Variables
This is optional if you are going to render your frontend with Jinja, you can have something close to MVC pattern
It would look something like this if you want to add views.
It is good to have your tests inside your backend folder.
Create them independently by APIRouter, instead of gathering all your APIs inside one file.
You can use absolute import for all your importing since we are using
__init__ everywhere, see Python’s packaging docs.
So assume you are trying to import v1’s endpoint.py from v2, you can simply do
from my_project.v1.endpoints.endpoint import something