dev.to flask heroku
To deploy a Flask application on Heroku, you can follow these steps:
- Set up a virtual environment:
- Create a new directory for your project.
- Open a terminal and navigate to the project directory.
- Create a virtual environment by running the command:
python3 -m venv env
Activate the virtual environment by running the command:
source env/bin/activate
Install Flask and other dependencies:
- Install Flask by running the command:
pip install flask
If your application has additional dependencies, you can install them by running the command:
pip install <dependency-name>
Create a Flask application:
- In your project directory, create a Python file (e.g.,
app.py
) and open it in a text editor. - Import the necessary modules:
from flask import Flask
- Create an instance of the Flask class:
app = Flask(__name__)
Define a route and a view function:
@app.route('/') def hello(): return 'Hello, World!'
Create a requirements.txt file:
- In your project directory, create a file named
requirements.txt
. Add the dependencies of your Flask application to this file, one per line. For example, if you have Flask as a dependency, add
Flask
to the file.Create a Procfile:
- In your project directory, create a file named
Procfile
(without any file extension). Add the following line to the file:
web: gunicorn app:app
Initialize a Git repository:
- Run the command:
git init
- Add all the files to the repository:
git add .
Commit the changes:
git commit -m "Initial commit"
Create a Heroku app:
- Install the Heroku CLI if you haven't already.
- Log in to your Heroku account by running the command:
heroku login
- Create a new Heroku app by running the command:
heroku create
Note down the URL of your Heroku app.
Deploy your Flask application:
- Add the Heroku remote to your Git repository by running the command:
heroku git:remote -a <heroku-app-name>
Push your code to the Heroku remote:
git push heroku master
Open your Flask application in a web browser:
Run the command:
heroku open
Test your deployed Flask application:
- Open the URL of your Heroku app in a web browser.
- You should see the output of your Flask application's route.
That's it! Your Flask application is now deployed on Heroku. You can make changes to your code and push them to Heroku whenever needed.