DEV Community

Cover image for Deploy your flask app on Heroku
Vishnu Sivan
Vishnu Sivan

Posted on

Deploy your flask app on Heroku

Heroku is a container based cloud platform as a service (PaaS) which is used for deploying your applications on the web. It received interest in recent years due to its simple setup and budget friendly pricing. Flask is a python based web application framework used to create APIs. Its simplicity makes it the default choice for building small APIs.

In this article, we will learn to create a simple flask application and deploy it on Heroku.

Getting Started

Prerequisites

  • python 3.8
  • heroku cli
  • git
  • postman Download the above software from the official site. Install them on your machine. Don’t forget to select the “add to path” option while installing python.

Verify the software installation version by the following command

python --version
heroku --version
git --version
Enter fullscreen mode Exit fullscreen mode

Install dependencies

  • virtual environment — It is used to manage the package installation in the machine and avoid the global installation of packages. Use the following command to install it on your machine, python -m pip install --user virtualenv
  • Create a virtual environment for our project using the following command
python -m venv venv
Enter fullscreen mode Exit fullscreen mode
  • Activate the virtual environment using the following command
  • In Windows machines,
venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  • In Linux machines,
venv/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • flask — It is a python based web application framework. Use the following command to install it on your machine,
pip install flask
Enter fullscreen mode Exit fullscreen mode
  • gunicorn — It is a pure Python WSGI server. Heroku requires gunicorn to deploy the flask app on the container. Use the following command to install it on your machine,
pip install gunicorn
Enter fullscreen mode Exit fullscreen mode

version

venv
flask
gunicorn

Create a flask app

Flask is a small and lightweight python framework used for creating web applications.

  • Create a file, app.py and add the following code to it.
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
    return '''<h1>Hello World</h1>'''
@app.route("/login",  methods = ['POST'])
def convert():
    user = request.get_json()
    if(user['username'] == 'admin' and user['password'] == '1234'):
        return jsonify({'success': True, 'message': 'Valid user'})
    return jsonify({'success': False, 'message': 'Invalid user'})
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)
Enter fullscreen mode Exit fullscreen mode

Understand the code,

  • Import the flask library, request and jsonify methods to get api request information in the json format.
  • Create a flask app using flask.Flask(__name__)
  • Create a default get route (‘/’) and return a Hello World header text as the response.
  • Create a /login route to get user information and return a json response which contains success and message values.
  • Run the server on 5000 port using app.run(host=”0.0.0.0", port=5000)

Run the app

Start your basic flask server using the following command

python app.py
Enter fullscreen mode Exit fullscreen mode

run the app
You can see two URLs in the terminal if the server is up and running.

To test our apis,

  • Open any browser and type any of the URL which is listed on the terminal.

output

  • Open postman and select the POST option. Type http://127.0.0.1:5000/login in the input box and provide username and password in json format in the body.

output 2

Create Heroku configuration files

Heroku requires some specific files in the directory while hosting the flask app on the cloud.

  • requirements.txt — It contains a list of the package names and the corresponding versions that are used in the project. Create requirements.txt file using the following command.
pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode
  • .gitignore — It contains a list of untracked files and directories that Git should ignore. Create .gitignore file using the following command.
echo venv/ > .gitignore
Enter fullscreen mode Exit fullscreen mode
  • Procfile — It specifies the commands that are executed by the app on startup. Create Procfile using the following command.
echo web: gunicorn app:app > Procfile

Enter fullscreen mode Exit fullscreen mode

config

Deploy the app

We have completed the basic flask api creation and the heroku specific file creation. Now, we can deploy the app on heroku.

  • Login to the Heroku account in the browser. Create a Heroku account from the link https://signup.heroku.com if you don’t have one.
  • Click on New → Create new app from the dashboard.

heroku 1

  • Provide a valid app name and click on Create app button to create the app. Leave the region and pipeline option as default.

heroku 2

  • Login to the heroku cli using the following command
heroku login
Enter fullscreen mode Exit fullscreen mode

heroku login

  • Execute the commands listed on the Deploy tab to deploy your flask app on the Heroku cloud. Skip the cd command if you are already on the app root folder.
git init
heroku git:remote -a flask-server-v1
git add .
git commit -am "make it better"
git push heroku master
Enter fullscreen mode Exit fullscreen mode

heroku git:remote -a flask-server-v1 may change according to your flask app name.

heroku hosting 1
heroku hosting 2

You will get a message as https://flask-server-v1.herokuapp.com/ deployed to Heroku, if the deployment is successful.

Instead of 127.0.0.1 you can use the host address given in the message to access the apis.

Great! Your flask server is live and up running on the cloud.

output 3
output 4

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

The article is also available on Medium.

The full source code for this tutorial can be found here,

GitHub - codemaker2015/heroku-flask-app: flask app configured for hosting on the heroku cloud

Useful links,

Top comments (2)

Collapse
 
tinabowman profile image
TinaBowman

excellent concept you have chooses to shared with us . with this help i can mange different things . kamakhya vashikaran mantra

Collapse
 
codemaker2015 profile image
Vishnu Sivan

I am glad to hear that.