The basics
This page introduces the API tools one by one, for someone who has never used them.
Python and pip
Python is the API's language. pip installs the libraries listed in api/requirements.txt. We work in a virtual environment (.venv/) so these libraries do not mix with the system's.
Django: the framework
provides the whole skeleton of a web application:| What Django handles | In the project |
|---|---|
| Settings | trinity_api/settings.py, read from |
| Addresses | trinity_api/urls.py |
| Tables | the models, in products/models.py |
| Table changes | the , in products/migrations/ |
| An admin interface | /admin/ |
A Django project is split into applications. Here there is only one: products.
The ORM
The turns the table into a Python class. You write:
Product.objects.filter(stock=0)and Django generates the SQL SELECT … WHERE stock = 0. The same code works with PostgreSQL and with SQLite.
Migrations
When you change a model, you run python manage.py makemigrations: Django writes a file describing the change. python manage.py migrate applies these files to the database, in order. See Database.
Django REST Framework: the API
(DRF) adds what a needs:| DRF building block | Role | In the project |
|---|---|---|
| Serializer | Product → JSON, and JSON → checked product | ProductSerializer |
| ViewSet | The list, retrieve, create, update, destroy operations | ProductViewSet |
| Router | Creates the addresses from the ViewSet | DefaultRouter in urls.py |
Gunicorn: the production server
python manage.py runserver is handy in development, but it is not made for production. In prod, starts 3 processes of the application, through the interface.
pytest and flake8
- pytest (with
pytest-django) runs the tests inproducts/tests.py, on a temporary SQLite database. - flake8 is the Python : it checks style (PEP 8) and obvious errors.