How to Deploy a Flask app on Heroku.
Trilochan Parida

Trilochan Parida @techparida

About: #TechEntrepreneur, Passionate about #technology #coding, Love to #troubleshoot #travel

Location:
India
Joined:
Jun 1, 2020

How to Deploy a Flask app on Heroku.

Publish Date: Jul 4 '20
61 16

Hello Friends, In this article I will show you how to deploy a flask app on Heroku. Follow the below steps to deploy your python flask app on Heroku.

Prerequisite:

  1. You must have installed Git in your system.
  2. You must have installed Python in your system.

Step-1: Install Heroku CLI

% brew tap heroku/brew && brew install heroku
Enter fullscreen mode Exit fullscreen mode

Above command is for Mac, for other systems you can click here

Step-2: Create Python Virtual Environment

% python3 -m venv foldername
% source foldername/bin/activate
% cd foldername
Enter fullscreen mode Exit fullscreen mode

Step-3: Install Flask & Gunicorn

% pip3 install flask gunicorn
Enter fullscreen mode Exit fullscreen mode

Step-4: Create an app folder and simple python app

% mkdir app
% cd app
% vi main.py
Enter fullscreen mode Exit fullscreen mode

main.py

from flask import Flask
app= Flask(__name__)
@app.route('/')
def index():
  return "<h1>Welcome to CodingX</h1>"
Enter fullscreen mode Exit fullscreen mode

Step-5: Create an entry point to the application, wsgi.py

% cd ../
% vi wsgi.py
Enter fullscreen mode Exit fullscreen mode

wsgi.py

from app.main import app
if __name__ == "__main__":
  app.run()
Enter fullscreen mode Exit fullscreen mode

Step-6: Run the application in your local system

% python wsgi.py
Enter fullscreen mode Exit fullscreen mode

Step-7: Create requirements.txt and Procfile file

% pip3 freeze
% pip3 freeze > requirements.txt
% vi Procfile
Enter fullscreen mode Exit fullscreen mode

Procfile

web: gunicorn wsgi:app
Enter fullscreen mode Exit fullscreen mode

Step-8: Create an app in Heroku

Heroku new app

Step-9: Deploy your app to heroku

% heroku login
% git init
% heroku git:remote -a codingx-python
% git add.
% git commit -am "First python app"
% git push heroku master
Enter fullscreen mode Exit fullscreen mode

Step-10: Open your application on browser

https://app-name.herokuapp.com

It's done!

Please Subscribe to my Youtube Channel https://youtube.com/c/codingx

Comments 16 total

  • Jon Nordland
    Jon NordlandJul 17, 2020

    Thank you, Very good. More people should focus on succinct explanations like this.

  • Kirtan Magan
    Kirtan MaganDec 12, 2020

    Thanks omg you are thebest =ever!!!!1!!!!

  • zeybep
    zeybepJan 20, 2021

    Hi,
    Firstly thank you very much ... I have to python files and they are in the same folder, named app folder... one is main.py and the other is sendemail1.py and there is wsgi.py file under the virtual directory. But when i run the wsgi.py it gives me the ModuleNotFoundError: No module named 'sendemail1' error so i can not push to heroku...


    my wsgi.py is;

    from app.main import app

    if name == "main":
    app.run()


    main.py file is:

    from flask import Flask, render_template, request
    from flask_sqlalchemy import SQLAlchemy
    from sendemail1 import sendemail

    from sqlalchemy.sql import func
    ...
    app= Flask(name)
    app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:123456@localhost/height_collector'

    class Data(db.Model):
    tablename="data"
    id=db.Column(db.Integer,primary_key=True)
    email_=db.Column(db.String(120),unique=True)
    height_=db.Column(db.Integer)

    def __init__(self,email_,height_):
        self.email_=email_
        self.height_=height_
    
    Enter fullscreen mode Exit fullscreen mode

    @app.route("/")
    def index():
    return render_template("index.html")

    @app.route("/success",methods=['POST'])
    def success():
    if request.method=='POST':
    email=request.form["email_name"]
    height=request.form["height_name"]

        print(email)
        if  db.session.query(Data).filter(Data.email_ == email).count() == 0:
            data=Data(email,height)
            db.session.add(data)
            db.session.commit()
            #average calculate
    
            avg_height=db.session.query(func.avg(Data.height_)).scalar()
            avg_height=round(avg_height,1)
            print(avg_height)
            count = db.session.query(Data.height_).count()
            sendemail(email,height,avg_height,count)
    
            return render_template("success.html")
    
    return render_template("index.html",
    text="Seems like there is an email already :)")
    
    Enter fullscreen mode Exit fullscreen mode

    if name=='main':
    app.debug=True
    app.run()


    sendemail1.py file is

    from email.mime.text import MIMEText
    import smtplib

    def sendemail(email,height,avg_height,count):
    from_email="usertestblabla@gmail.com"
    from_password="eee134566"
    to_email=email

    subject="Height Data"
    message ="Hey , your height is <strong> %s. <strong> Average height of all is %s and calculated out <strong> %s <strong> of people. " % (height, avg_height,count)
    
    msg = MIMEText(message,'html')
    msg['Subject']=subject
    msg['To']=to_email
    msg['From']=from_email
    
    gmail=smtplib.SMTP('smtp.gmail.com',587)
    gmail.ehlo()
    gmail.starttls()
    gmail.login(from_email,from_password)
    gmail.send_message(msg)
    
    Enter fullscreen mode Exit fullscreen mode

    thank you very much

    • zeybep
      zeybepJan 20, 2021

      Hi again,
      i found the error...It is because i have to write the import like this
      from app.sendemail1 import sendemail to the main.py
      than it works
      have a great day

  • Edung Divinefavour
    Edung DivinefavourApr 11, 2021

    Super useful!!!!!!!!!

  • Luv2bnanook44
    Luv2bnanook44Jun 7, 2021

    thank you!!!

  • Mohsin Ashraf
    Mohsin AshrafSep 4, 2021

    Thanks great tutorial.

  • Hanzala Khan
    Hanzala KhanSep 16, 2021

    Hey I have a simple endpoint on my Herokuapp bloggir.herokuapp.com/d and i want to fetch it with JS fetch API, it is giving an error.please help

  • Sara García
    Sara GarcíaOct 21, 2021

    Thank you so much!! Very well explained

  • billy_dev
    billy_devNov 6, 2021

    I like the tutorial, Thank you.
    My question is how do is set a port and a database that isn't a local storage on like: sqlite, to using postgresql?

  • Pathum Lakshan
    Pathum LakshanNov 12, 2021

    Neat work Thanks lot

  • The Phantom Coder
    The Phantom CoderNov 14, 2021

    Thanks, this was quick and easy and it worked perfectly for me.

  • Dasith Rathnasinghe
    Dasith RathnasingheNov 28, 2021

    Thank you. very useful

  • davidkiama
    davidkiamaFeb 27, 2022

    Thanks mate!

  • Thomas Rettig
    Thomas RettigJun 22, 2022

    OMG!!! THANK YOU SO MUCH!!! I was spending the past few days struggling to deploy my Flask app to Heroku, and then I stumbled across your article. After a few modifications, the site is now in production! :D

Add comment