A sample Python webapp that intends to showcase best practises regarding:
- most importantly a great http server (FastAPI)
- project structure
- all-around asynchronous IO
- config management
- dependency injection (provided by FastAPI)
- input validation (provided by FastAPI)
- unit and integration testing
- code style (flake8, isort)
- package management (Poetry)
Clone the repo:
$ git clone https://github.com/peterdeme/python-sample-app.gitInstall Poetry if you haven't already. This project requires 1.0 which is currently in beta as of November 2019.
$ curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | POETRY_VERSION=1.0.0b4 pythonCreate your own configuration from the template:
$ cp .env-template .envSetup the Postgresql connection string in .env file. The default connection string points to a local Dockerized instance which you can easily pull up with:
$ docker-compose up -d pgsqlInitialize the database schema:
$ poetry run alembic upgrade headFinally, run the app:
$ poetry run python -m app.appIn another cmd window test if it works:
$ curl http://localhost:8000/api/v1/articles && echoOr just open the above URL in a browser.
Use the following interpeter in your IDE:
$ poetry run which pythonHere's a sample debug config for VS Code users:
.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch app",
"type": "python",
"request": "launch",
"module": "app.app"
}
]
}In production you'll most probably want to run a webapp in Docker. This repository contains a Dockerfile which aims to be a good example for a production service. You can try it locally:
$ docker-compose upAs per the official recommendation, the app uses Gunicorn as a green "worker manager" which spawns Uvicorn worker processes.
Type check:
$ poetry run mypy app --config-file tox.iniAutofix flake8 issues with autopep8:
$ poetry run autopep8 -r -i .Sort imports:
$ poetry run isort -rc .Run tests:
$ poetry run pytest