This article guides you through the steps to deploy a fresh Python Flask app to Heroku. I am a Mac user and my IDE of choice is PyCharm, but you can adapt this tutorial to your own environment easily.
Source code of this sample project is available on GitHub.
First, register a new account on www.heroku.com .
Download & install the command line tools at https://devcenter.heroku.com/articles/getting-started-with-python#set-up . Enter terminal and enter the command:
Your credentials will be asked. Enter them, and you’ll be in contact with Heroku.
Define a new Flask project in PyCharm. I will call it Helloku2 . When you run the app locally, you should be seeing a web page.
To prepare your app for live usage, we need a real web server. Add gunicorn to your project. In the terminal, ensure you can start the app by typing:
The application should be accessible in your browser. You can terminate the application with CTRL+C.
Prepare project for Heroku
Create a new file called Procfile (no extension) in the root of your application, which contains one line:
web gunicorn app:app
This will tell Heroku that this is a web application, and start it with gunicorn (like in the terminal).
Go to the terminal and type:
pip freeze > requirements.txt
This command will put all of your dependencies into a file called requirements.txt . Heroku will use this file to build your virtual environment on the server side.
Click the menu VCS -> Enable and select Git. Select “Commit” from the toolbar, and make it ignore .idea and venv folders. Click “Commit” to complete the operation.
Submit to Heroku
First, we need to create a new app. Go to terminal and type:
heroku create helloku2
This will create a new application called helloku2. If this name is taken on Heroku, you might need to pick a new name. To enable it for git, type:
heroku git:remote -a helloku2
Finally, type the following command to submit your app:
git push heroku master
Run on Heroku
You start by assigning your app some server resources by typing:
heroku ps:scale web=1
That’s all! When you enter https://helloku2.herokuapp.com/ , you see your application running on the web.
To stop your application, you simply scale it down to zero by typing:
heroku ps:scale web=0
You can also see your applications on www.heroku.com , under your account dashboard.
It is a common task to set & use environment variables in PyCharm.
You can set an environment variable in Heroku by typing:
heroku config:set GITHUB_USERNAME=joesmith
You can remove an environment variable from Heroku by typing:
heroku config:unset GITHUB_USERNAME
You can list your Heroku environment variables by typing: