A Heroku Python Flask website application

We have been talking about Heroku applications using Python, where we can set up Python based web hosting without the need to work around Apache to get a python based web site running. In our python website example we use the flask library instead of Apache for the server.

The simplest 'Hello World' flask application is easy to find. It is on the Heroku website as well as in documentation that can be found for the Flask modules. Nonetheless, here it is again:

1
2
3
4
5
6
7
8
from flask import Flask
 
app = Flask(__name__)
@app.route('/')
def hello():
 return 'Hello World!'
if __name__ == '__main__':
 app.run('')

To simplify using flask, lets just run this application on our Ubuntu computer to 127.0.0.1

To do this, we need to have the Flask library available to applications.

    pip install flask

Then, all we need to do to see our 'Hello World' application is this:

    python hello.py

Holy strawberries Batman! We've got a website! Does Heroku work this simply? No, the Heroku version of Hello World contains two extra lines of code, and uses the OS module for Python, so to conclude today's discussion about simple python web site applications, here is the Heroku version of Hello World.

1
2
3
4
5
6
7
8
9
10
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
 return 'Hello World!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
 port = int(os.environ.get('PORT', 5000))
 app.run(host='0.0.0.0', port=port)

If you don't believe me, go to the www.heroku.com website, they really deserve the credit, because I cut and pasted this example from them. Two lines of code are added to the main execution body of the example, first the variable 'port' is set with the results of an operating system call and that is provided for the app.run command.

Can you think of a way to turn this into a single line of code? If you can, you have started to read and understand Python, and hopefully look forward to our next discussion on Python Flask Heroku applications. See you later, alligator! 




Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved