A flask app structure with the following features:
- RESTful API with marshmallow validation
- Users and roles SQLAlchemy models
- PostgreSQL and MySQL support
- Migrations versioning
- Runtime logging
- Unittests with Pytest
- Swagger documentation
- Docker Hub deployment
- CI/CD pipelines with GitHub Actions
- Production-ready Docker Compose setup with Gunicorn
- Create a python3.11 venv within the project's root directory and set up the environment:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install -y python3.11 python3.11-dev python3-venv
python3.11 -m venv venv
. venv/bin/activate
pip install -r src/requirements.txt
- Export the following environment variables (modify the values as needed):
export _ADMIN_PASS=admin
export _SECRET_KEY=ABCDEFGH12345678
export _DB_PROVIDER=postgresql
export _DB_DATABASE=flask-app
export _DB_HOST=172.17.0.2
export _DB_PASS=admin
- Sample of a PostgreSQL and MySQL databases using docker:
# postgres
docker run -dit \
--name flask-app-database \
-p 5432:5432 \
-e POSTGRES_DB=flask-app \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=admin \
postgres:latest
# mysql
docker run -dit \
--name flask-app-database \
-p 3306:3306 \
-e MYSQL_DATABASE=flask-app \
-e MYSQL_USER=admin \
-e MYSQL_PASSWORD=admin \
-e MYSQL_RANDOM_ROOT_PASSWORD=True \
mysql:latest
Before starting the application it is essential to upgrade the database to the latest migration version and populate it with the default user/admin roles. Within the src
directory:
- Upgrade database:
flask db upgrade
- Populate database:
flask populate_roles
- Development mode:
flask --debug --app src.app -h 0.0.0.0 -p 8080
- Production mode:
gunicorn --bind 0.0.0.0:8080 --threads 64 --worker-class gthread --workers 4 --worker-connections 8192 "src.app"
To run the application with docker compose, follow these steps within the docker-compose
directory:
- Rename the
template.env
file to.env
and fill the variables with real values - Run:
docker compose up
Optionally, you can build a local docker image within the src
directory:
- Export the Docker Hub environment variable:
export DOCKERHUB_REPO=your_repo
- Run:
make
For the Docker Hub job to work properly in GitHub Actions pipelines, it is required to set the following variables in the GitHub Actions secrets:
- The Docker Hub username/password is your Docker Hub login credentials.
- The Docker Hub token is a JWT that authenticates the user with Docker Hub APIs.
DOCKERHUB_USER=username
DOCKERHUB_PASS=p4ssw0rd
DOCKERHUB_TOKEN=s3cr3t_t0k3n
- The unittests can be executed using either pytest or with coverage. Within the project's root directory:
export _TESTING=1
python3 -m pytest src/tests/unittests
coverage run -m pytest src/tests/unittests && coverage report -m
- The API is fully available and documented through the Swagger apidocs at:
http://0.0.0.0:8080/apidocs
.