Deploying to Production
Deploying our Stock Quote application using Heroku
Deploying to production
Now that we have an application that works, we can put it up on the internet. This book will cover a few different deployment methods later on, but for now, we're going to use Heroku, a commonly used Platform as a Service host were we can directly upload our application to take care of a lot of the behind the scenes infrastructure level work.
We're going to need to tell Heroku what command to run our Flask application. To date, we've been using the bundled server that comes with Flask to view the application within our own browser, however using it to serve real traffic is discouraged. What we'll do instead is use a production grade server library to serve our application (which Heroku will route end users to).
Herkou is going to look at our
requirements.txt file to see what libraries to install, so we'll need to add our server library called gunicorn to this file.
flask requests gunicorn
Then we're going to need to tell Heroku how to run our web application. To use gunicorn, we need to point it to the python file that hosts our Flask application and what variable references the Flask application object.
In addition, we'll want to tell it to listen on the IP address and port
0.0.0.0:5000 which means that it'll be listening and respond on port 5000. Heroku uses that port by default to talk to our application.
Heroku uses a file called a
Procfile (which is short for Process File) and we can define commands under each kind of "worker". To serve a web application, we'll want to define a "web" worker with the gunicorn command. The $PORT environment variable will be specified by Heroku and is what it'll be expecting that our Flask application is serving on.
web: gunicorn --bind 0.0.0.0:$PORT server:app --log-level "debug"
To install the Heroku command line interface, you can go to the download page available at the Heroku website and walk through the installer for your operating system. The full setup instructions for Python applications is available at Heroku's Pytho n Documentation
After following the Heroku CLI setup, the next step to do deploy is run
heroku create within our application folder and then push to a
git repository hosted on Heroku.
(env) $ heroku create Creating app... done, ⬢ cryptic-reef-51053 https://cryptic-reef-51053.herokuapp.com/ | https://git.heroku.com/crypt ic-reef-51053.git (env) $ git init . Initialized empty Git repository in [your folder]/.git/ (env) $ git add . (env) $ git commit -m 'Add untracked files' [master (root-commit) 109b1d4] Add untracked files 6 files changed,