Deploy Flask, psql & SQLAlchemy app to Heroku

Deploy Flask Application to Heroku

1 Install Gunicorn

python3 -m pip install gunicorn

2 Export dependencies to requirements.txt


pip freeze > requirements.txt

3 Create a Procfile

Add the file to be run by heroku. In this case the manage.py file is run

web: gunicorn manage:app

4 Create heroku app

heroku login

After successful login

heroku create <name of app>

5 Add configurations - These are all the exports in your application.

heroku config:set <KEY OF THE VARIABLE>= <VALUE>

eg heroku config:set api_key=abcffddffd

6 Push to heroku

git add .
git commit -m "deploy ..."
git push heroku master

master can be main, depending on how you named your default local branch

Deploying the database

7 Add export configs related to the database

heroku config:set <KEY OF THE VARIABLE>= <VALUE>
heroku addons:create heroku-postgresql:hobby-dev

Hobby dev refers to the hosting plan on heroku

8 Update the SQL Alchemy URI for production environment

SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL').replace("://", "ql://", 1)

9 Update the environment you use to initalize app


app=create_app('production)

10 Push the changes

git add .
git commit -m "deploy ..."
git push heroku master

11 Run the db upgrade

Prefix the command you use to do migrations with 'heroku run'

using flask cli

heroku run flask db upgrade

direct file run

heroku run python3 manage.py db upgrade

Handling db upgrade issues

Create the migrations afresh

1 Destroy the databases in heroku

use heroku pg:info to check the database

destroy using:

heroku addons:destroy <NAME OF DATABASE WITHOUT _URL SUFFIX>

EG if the database is DATABASE_URL

heroku addons:destroy DATABASE

2 DROP the local database and create it again.

$ psql

$ DROP DATABASE <name of database>
$ CREATE DATABASE <name of database>

3 Delete the migrations folder

4 Run migrations again (locally) -This will create the migrations folder again.


python3 manage.py db init

python3 manage.py db migrate -m "message"

python3 manage.py db upgrade

5 Push your work to heroku

6 Recreate heroku database

7 Run upgrade on heroku

Extras

To access the heroku psql interface use

heroku pg:psql

You can insert data if you wish