Deploy a Flask App on Heroku and Connect it to a JawsDB-MySQL Database | by Edward Krueger | Towards Data Science

By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer.
In this article, we’ll cover how to deploy an app with a Pipfile.lock to the cloud and connect the app to a cloud database. For more information on virtual environments or getting started with the environment and package manager Pipenv, check out this article!
Newer developers often install everything at the system level due to a lack of understanding of, or experience with, virtual environments. Python packages installed with pip are placed at the system level. Retrieving requirements this way for every project creates an unmanageable global Python environment on your machine. Virtual environments allow you to compartmentalize your software while keeping an inventory of dependencies.
Pipenv, a tool for virtual environment and Python package management, allows developers to create isolated software products that are easier to deploy, build upon, and modify.
Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and for creating, using, and managing your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product.
Heroku offers many software products, and we’ll need the Heroku cloud platform service to host an app and JawsDB to use a MySQL database. Don’t worry, creating an account and using these features is free!
We are going to use the Heroku GUI to deploy a database and a Python app.
In our previous deployment, we used an SQLite database. When using an SQLite database, every app redeployment will reset your database. Heroku’s JawsDB allows our data to persist through app updates. Additionally, hosting, configuring, patching, and managing the database is all done for you with JawsDB.
Heroku allows us to deploy an app from a GitHub branch. Once we have a working app with a Pipfile pushed to GitHub, we are ready to make some final changes to the repository to prepare for deployment. Be sure to have your Pipfile at the project’s root directory so Heroku can find it!
Note: These next changes allow our app to run on Unix systems. Gunicorn is not compatible with PCs, so you will not be able to test these changes locally if you are not using a Linux or Unix machine.
Gunicorn is a Python WSGI HTTP server that will serve your Flask application on Heroku. By running the line below, you add gunicorn to your Pipfile.
pipenv install gunicorn
Create a Procfile in the project root folder and add the following line:
web: gunicorn app:app
The first app represents the name of the python file that runs your application or the name of the module where the app is located. The second represents your app name, i.e., app.py. This Procfile works with gunicorn and Heroku's Dynos to serve your app remotely.
Set up an account with Heroku if you haven’t already, don’t worry all the features we show here are free!
Go to your app on Heroku.com and click resources. Then type “JawsDB MySQL” into the addons box, as seen below.
Select the free version and click provision. Great, we now have a MySQL database deployed for our app. Next, we need to integrate this new database into our app logic.
First, let’s add Pymysql, a Python SQL library, to our Pipfile with the following.
pipenv install pymysql
Now let’s get our connection string and modify it for pymysql. Go to settings and look at the configuration variables. You’ll find a connection string that resembles the one below.
mysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n
We need to make a change to the DB connection string so that it uses the Pymysql driver.
In a text editor, remove the mysql and add in its place mysql+pymysql and then save the updated string.
mysql+pymysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n
You’ll need to add this to your configuration variables on Heroku. To do this, go to settings, then config vars and update the connection string.
Create a new file called .env and add the connection string for your cloud database as DB_CONN,shown below.
DB_CONN=”mysql+pymysql://root:PASSWORD@HOSTNAME:3306/records_db”
Note: Running pipenv shell gives us access to these hidden environmental variables. Similarly, we can access the hidden variables in Python with os.
SQLALCHEMY_DB_URL = os.getenv(“DB_CONN”)
Be sure to add the above line to your database.py file so that it ready to connect to the cloud!
Once we have our app tested and working locally, we push all code to the master branch. Then on Heroku, go to deploy a new app to see the page below.
Next on Heroku, select GitHub, enter the name of the repository and hit search. Once your username and repository appear, click connect. Then select the desired branch and click deploy.
Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. If you don’t use Pipenv, you will need to have a requiremnts.txt for this build to occur. Once again, place these files at your project’s root.
Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message.
The app is successfully deployed! Click to view button to see the deployed app on Heroku.
You might run into an error where your tables have not been created before you attempt to get or post data. To solve this, we use the following line in our app.py.
@app.before_first_requestdef setup():     db.create_all()
We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch.
Coding and building useful software requires the management of complexity. We discussed Github as a version control tool, Pipenv as an environment and package manager and some benefits of having cloud companies manage your databases. These tools help reduce the complexity of building software so developers can focus on building rather than managing.
Practicing proper environment and package management is crucial for data scientists and developers who want their code deployed, built upon, or used in production. Using an environment and package manager such as Pipenv makes many processes, including deployment, more comfortable and more efficient!
Additionally, having a well managed GitHub master branch with a Pipfile allowed Heroku’s severs to rebuild our app with minimal troubleshooting. This lets us deploy an app from a project directory on GitHub to Heroku in minutes.
We hope this guide has been helpful and welcome comments and questions, thank you!