Heroku is increasingly becoming my favorite platform to deploy simple Python applications on. Heroku actually gives you a completely managed environment where you can deploy an app in literally minutes. Not to mention that the free tier usage on Heroku (1 dyno, Postgres dev plan) can actually get you pretty far.
You can follow the official docs on Heroku that explain how to get started from scratch, but I find them lacking some explanation on how to set up Postgres, so here’s the complete formula I use to rapidly deploy simple Python apps.
All the code in this post can be found in the matching repository on Github.
I’m going to assume you have a basic project setup, if not just follow the aforementioned tutorial. So now we need to add support for PostgreSQL. We’ll do that by using Flask-SQLAlchemy which will give us everything we need to connect to the Postgres DB as well as an easy to use ORM. So first we need to install the dependency and add it to our requirements.txt:
1 2 3 | |
Before we continue we’ll have to create the Postgres DB and we’ll start off with the free dev plan which allows for up to 10K rows and 20 simultaneous connections:
1 2 3 4 | |
Once the database is setup we should promote it such that the DATABASE_URL environment variable will be set:
1 2 | |
Now we can go ahead and import the library and add the basic connection boilerplate:
1 2 3 4 5 | |
For this step, you can optionally use Kenneth Reitz’s flask-heroku library, which handles setting all connection URLs automatically, not only for Postgres, but for other services such as redis, sentry, exceptional and others.
The next step is to commit the boilerplate code and create the actual DB tables:
1 2 3 4 | |
Once we have a connected Python terminal we can run:
1 2 | |
And we’re set! From here we can start using SQLAlchemy’s code to define models and create, query and delete objects. Here are some examples. We can start off by creating a new User model:
1 2 3 4 5 6 7 8 9 10 11 | |
We can create the object itself:
1 2 3 | |
We can query objects:
1
| |
And we can delete objects:
1 2 3 | |
And that’s all you need to know about setting up a Flask + Postgres app on Heroku.