cheeyeo / Flask_App_Demo

Example of building a Flask app with SQLAlchemy using Postgresql

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple Flask project

A simple messageboard project built in Flask with a Postgresql backend.

It's running in dev mode locally via docker compose

Uses:

  • Flask web framework
  • SQLAlchemy and flask-sqlalchemy for ORM
  • alembic for database migrations
  • flask-login for user logins
  • Docker and docker compose for application and postgresql db

To run locally with docker-compose:

Copy .env.example to .env and fill in required env vars.

To start both application and DB in terminal:

source .env

docker compose -f compose.yaml up

This will start up the postgresql DB first and after reaching a successful healthcheck, it will start the web application.

It creates a persistent docker volume for the database data.

The base database migration is ran automatically via entrypoint.sh script which is set as the enrtypoint for the dev image.

If changes are made to the database models, you need to generate a new migration using:

docker exec messageboard-web-1 alembic revision --autogenerate -m 'REASON FOR NEW MIGRATION'

docker exec messageboard-web-1 alembic upgrade head

If changes are made to the web app, it will reload the application code.

Building production image

To build production docker image, from the root folder, run:

docker build -t web:latest -f board/Dockerfile --target prod .

DATABASE MIGRATIONS

Handled by alembic

To generate baseline migrations for all the models' tables:

alembic revision --autogenerate -m 'Create baseline migrations

To run migration:

alembic upgrade head

Useful Alembic commands:

  • Display the current revision for a database: alembic current

  • View migrations history: alembic history --verbose

  • Revert all migrations: alembic downgrade base

  • Revert migrations one by one: alembic downgrade -1

  • Apply all migrations: alembic upgrade head

  • Apply migrations one by one: alembic upgrade +1

  • Display all raw SQL: alembic upgrade head --sql

  • Reset the database: alembic downgrade base && alembic upgrade head

More Alembic commands

DATABASE NOTES

  • To install psycopg2 we need to install the following dep on ubuntu:
sudo apt install libpq-dev

Then:

pip install pyscopg2

To install without any system deps:

pip install pyscopg2-binary
  • To connect to running postgresql container:
docker exec -it <container id> psql -U <username> <dbname>

References

TODO:

About

Example of building a Flask app with SQLAlchemy using Postgresql


Languages

Language:Python 68.5%Language:HTML 22.0%Language:CSS 4.5%Language:Mako 2.2%Language:Dockerfile 1.7%Language:Shell 1.1%