Flask and PostgreSQL on Heroku

Keywords: Python PostgreSQL Attribute Session

Links to the original text: Flask and PostgreSQL on Heroku

Heroku is becoming my favorite platform for deploying simple Python applications. Heroku actually provides you with a fully managed system, and you can deploy your application in just a few minutes. Not to mention that its free version (1 dyno, Postgres dev plan) actually gives us more to do.

You can follow the official document on Heroku, which gives you How to start from scratch But I found that it lacked some instructions on how to set up Postgres, so I gave a complete tutorial on rapid deployment of simple Python applications.

All the code used in this article is available in matching repository on Github. Find it.

Here, I will assume that you have a basic project foundation. If not, please refer to the previous tutorial. Then we need to add support for PostgreSQL. We use Flask-SQLAlchemy To do this, it provides everything connected to Postgres DB and makes ORM easy to use. So first we need to install this dependency and then add it to our requirements.txt.

1 $ pip install flask-sqlalchemy psycopg2
2 # don't forget to update requirements.txt
3 $ pip freeze > requirements.txt

Before continuing, we need to create a Postgres DB, and then we will start with a free development plan that allows up to 10K rows and 20 concurrent connections:

1 $ heroku addons:add heroku-postgresql:dev
2 -----> Adding heroku-postgresql:dev to some-app-name...done, v196 (free)
3 Attached as HEROKU_POSTGRESQL_COLOR
4 Database has been created and is available

Once the database is established, we should promote it, and then the DATABASE_URL environment variable will be created:

$ heroku pg:promote HEROKU_POSTGRESQL_COLOR
Promoting HEROKU_POSTGRESQL_COLOR_URL to DATABASE_URL... done

Now we can move on, import libraries and add basic connection templates:

from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)

For this step, you can choose to use Kenneth Reitz's flask-heroku library, which can automatically process all connection URLs, not only for Postgres, but also for other services, such as redis, sentry, exceptional and other services.

The next step is to submit the template code and create the DB table:

$ git commit -a -m "added DB boilerplate"
$ git push heroku master
# ...
$ heroku run python

Once we connect to the Python terminal, we can execute:

>>> from app import db
>>> db.create_all()

We set it up! From here, we can start using SQLAlchemy code to define models and create, query and delete targets. Here are some examples. We can start by creating a new User model:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)

    def __init__(self, name, email):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<Name %r>' % self.name

We can create objects themselves:

user = User('John Doe', 'john.doe@example.com')
db.session.add(user)
db.session.commit()

We can query the target:

all_users = User.query.all()

We can also delete the target:

user = User('John Doe', 'john.doe@example.com')
db.session.delete(user)
db.session.commit()

This is what you need to know about setting up Flask + Postgres applications on Heroku.

Posted by pitn on Fri, 14 Dec 2018 19:00:03 -0800