220512 Lab 3: Flask, SQLAlchemy, Prometheus client - arashafazeli/bb-readme-tutorials GitHub Wiki

2022-05-12

Intro

All files you need for this lab is in the repo here. All code in backend.py is explained here

Goals for this lab

Create a backend to a simple message board.

  • Set up a backend API with Flask.
  • Create 3 endpoints: messages and comments and metric
  • Use SQLAlchemy and PostgreSQL (PostgreSQL in docker container)
  • Prepare for Prometheus

Requirements

Install and Activate virtual environment

sudo apt-get install python3-pip
sudo pip3 install virtualenv
virtualenv -p /usr/bin/python3.9 venv
source venv/bin/activate

Install PostgreSQL in docker container

sudo apt install docker-compose
sudo chmod 666 /var/run/docker.sock
docker-compose -f postgres.yml up
sudo apt install postgresql-client
cat schema.sql | psql -h localhost -U postgres -d postgres

Install Requirements

pip install -r requirements.txt

Start Flask API

FLASK_APP=backend flask run

To activate debug mode (restarts every time after saving the file)

FLASK_ENV=development FLASK_APP=backend flask run

Start a new terminal instance to continue testing!

Testing Flask API messages

curl -X POST -d "author=breaking_bad" -d "title=Message created via curl" -d "text=curl rocks" http://localhost:5000/messages
curl -X GET  http://localhost:5000/messages -v

Testing Flask API comments

curl -X POST -d "author=bad" -d "text=This is a comment" -d "parent=1" http://localhost:5000/comments
curl -X GET  http://localhost:5000/comments -v 

Testing Flask API metrics

curl -X GET  http://localhost:5000/metrics -v 

This backend is used in Lab 4