Deploying Application is fun. But it has some of the issues to host when you want to deploy your app to a free service.
Heroku
is one of the most popular PaaS
( Platform
as a Service) that provides a great support to host your application online.
Let's see how we can easily deploy a Simple Python Web Application
(Flask
) to Heroku.
Before you start to follow along this gist please download the heroku CLI
There are 3 main tasks to perform for a successful deployment.
- Registeting or Creating the App.
- Adding Necessary Files.
- Deployment on the Server.
- Open terminal on the root of the project.
- Run the following,
This would prompt the browser for the user authentication. Complete that.
heroku login
- Now run,
Your name you provided for the application must be available for the platform, and if it is available, this will create a
heroku create <your_desired_app_name>
git repo
in heroku server and you will get a valid url of your application.
-
Prepare your Project. For the demo, we will be writing all out codes in
serve.py
file. Here is the code.# -*- coding: utf-8 -*- """ author: S.M. Sabbir Amin date: 02 May 2020 email: sabbir@rokomari.com, sabbiramin.cse11ruet@gmail.com """ import os from flask import Flask, jsonify app = Flask(__name__) app.secret_key = 'nooneissafe' @app.route('/') def index(): response = { "hello": "world" } return jsonify(response) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run( host="0.0.0.0", port=port, debug=True )
-
Add a
Procfile
. In it, write what kind of application it is. Here,web: python serve.py
This means that the applicaton is a Web type of Application and it will run by
python
interpreter. Python Interpreter will runserve.py
file in this case for the incoming web request. -
Add
runtime.txt
file and write only the runtime supported by Heroku. Here,python-3.6.10
-
Add
requirements.txt
file and add the external libraries or modules your need to run the Application. Use eitherpip
orpipreqs
to generaterequirements.txt
file.-
pipreqs <root_of_the_project_directory>
-
-
Init Git in the root of the porject directory, unless it is not done already.
git init
-
Add the Changes.
git add .
-
Commit the changes, made.
git commit -m "<your Message Here>"
-
You can push directly to the
master
branch of the Heroku Repo. If you chose other branch thanmaster
, it would deny to build the application. There is workaround.git push -f heroku <branch_name>:master
This would push your non
master
branch to the master branch of heroku and continue to build.If you choose to push the master branch, this is simply
git push heroku master
-
For going through the logs, just run
heroku logs
To see the log stream, run
heroku logs --tail
See? This is easy. Try to code. Try to Deploy. Ciao.