Deploying a Flask Application to Heroku

A Step-by-Step Guide

Introduction

In this tutorial, we will walk through the process of creating a simple Flask application and deploying it to Heroku. This guide is aimed at beginners and will cover everything from setting up a Flask app to its deployment on Heroku.

What You Will Need

  • Basic understanding of Python
  • A Heroku account
  • Git installed on your computer

Step 1:

Setting Up Your Flask Application

First, let’s look at the app.py file, which is the heart of our Flask application.

app.py

				
					from flask import Flask
import os

app = Flask(__name__)

@app.route('/')
def greeting():
    return 'Welcome to Ucleus lab 54!'

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
				
			

This code creates a basic Flask web app with a single route (/) that returns a greeting message.

Step 2:

Preparing for Deployment

Before deploying, make sure your requirements.txt file lists all the necessary dependencies.

requirements.txt:

				
					Flask==2.3.2
gunicorn==21.2.0
				
			
(This code was created on 12/8/2023. The version of Flask and gunicorn code have been updated by the time you are following this.)

This file tells Heroku which packages are required for your application.

Step 3:

Creating the Procfile

A Procfile is necessary for Heroku to understand how to run your application.

Procfile:

				
					web: gunicorn app:app
				
			

This line instructs Heroku to use Gunicorn as the web server for running the app.

Step 4:

Deploying to Heroku

  1. Initialize and Configure Git: If you haven’t already, initialize a Git repository in your project folder and commit your files.
  2. Create a Heroku App: Use the command heroku create to create a new app on Heroku.
  3. Deploy: Push your code to Heroku using git push heroku master.
  4. View Your Application: Open your deployed app in a browser with heroku open.

Conclusion

Congratulations! You’ve just deployed a Flask application to Heroku. This basic setup is a stepping stone to more complex applications and functionalities.

Next Steps

  • Experiment with Flask to add more functionalities.
  • Learn about databases and how to integrate them into your Flask app.
  • Explore the Heroku documentation to understand more about deployment options and optimizations.

Add comment: