# Table of Contents * [Overview](#overview) * [Setting up the environment](#setting-up-the-environment) * [Install the requirements](#install-the-requirements) * [Setup the environment variables](#setup-the-environment-variables) * [The API](#the-api) * [The Database](#the-database) * [Workflow for updating database (new table/field/etc)](#workflow-for-updating-database-new-tablefieldetc) * [Initial DB Setup for the app](#initial-db-setup-for-the-app) * [Working with the database](#working-with-the-database) * [Adding to the database](#adding-to-the-database) * [Querying the database](#querying-the-database) * [Clear out the tables](#clear-out-the-tables) # Overview A simple flask application that includes a basic web frontend, with login, and a simple REST API # Setting up the environment ## Install the requirements ``` pip install -r requirements.txt ``` ## Setup the environment variables The following can be added to a `.env` file in the foot of this directory as well ```bash APP_ENVIRONMENT="PROD" SECRET_KEY="myverysecretkey" DATABASE_URL="sqlite:///app.db" ``` # The API The api allows for various functions. To work with it locally and easily, you can use `httpie` in Pypi or just use curl: ```bash pip install httpie ``` The following includes various methods: ```bash # Get token http --auth : POST http://localhost:5000/api/tokens # Revoke token http DELETE http://localhost:5000/api/tokens "Authorization:Bearer " # Create user http POST http://localhost:5000/api/users "Authorization:Bearer " username=alice password=dog email=alice@example.com # Update current user http PUT http://localhost:5000/api/users/1 "Authorization:Bearer " email=new_email@example.com # Various routes http GET http://localhost:5000/api/users "Authorization:Bearer " http GET http://localhost:5000/api/users/1 "Authorization:Bearer " ``` # The Database ## Workflow for updating database (new table/field/etc) 1. Export the flask app: `export FLASK_APP=stockpyle.py` 2. Create/modify class for table in `app/models.py` 3. Create migration script: `flask db migrate -m " table"` 4. Commit migration script to repo (for upgrading other environments) 5. Make the changes to the database: `flask db upgrade` ## Initial DB Setup for the app ```bash flask db upgrade ``` ## Working with the database ### Adding to the database ```python u = User(username='john', email='john@example.com') u.set_password('password') db.session.add(u) u = User(username='susan', email='susan@example.com') u.set_password('password') db.session.add(u) db.session.commit() ``` ### Querying the database ```python # get user u = User.query.get(1) u # # get all users in reverse alphabetical order User.query.order_by(User.username.desc()).all() #[, ] ``` ### Clear out the tables ```python users = User.query.all() for u in users: db.session.delete(u) db.session.commit() ```