This is our 2nd Post of the Flask Tutorial Series.

In this post we will be creating a "Hello, World" application to demonstrate how easy it is to run a Flask Appliation.

The only requirement you need to run this app, would be to to have Python, Pip and Flask installed.

Traditional Hello World Application:

Install the Flask package:

$ pip install flask

More details on setting up virtual environments will be demonstrated in the next post

Lets create the Hello World App:

from flask import Flask 

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

Save the above code as app.py and then run the application as follows:

$ python app.py
* Running on http://127.0.0.1:5000/

It's Running, What Now?

We can see that our application is running on 127.0.0.1 and listening on port: 5000, if you point your browser to this URL, you will be returned with:
'Hello, World!'

$ curl -i -XGET http://127.0.0.1:5000/
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/0.12.1 Python/2.7.12
Date: Thu, 30 Mar 2017 21:12:15 GMT

Hello, World!

What exactly did we do here?

  • First, we imported the Flask class from the flask module, using: from flask import Flask
  • Then we instantiate our application from the Flask class: app = Flask(__name__) using our module's name as a parameter, where our app object will use this to resolve resources. We are using __name__ , which links our module to our app object.
  • Next up we have the @app.route('/') decorator. Flask uses decorators for URL Routing.
  • Below our decorator, we have a view function, this function will be executed when the '/' route gets matched, in this case returning Hello, World!
  • The last line starts our server, and from this example it runs locally on 127.0.0.1 on port: 5000 and debug is enabled, so any error details will be logged directly in the browser.

Let's Extend our Hello World App:

We would like to add the route '/movie' which will return a random movie name:

import random
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

@app.route('/movie')
def movie():
    movies = ['godfather', 'deadpool', 'toy story', 'top gun', 'forrest gump']
    return random.choice(movies)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

Making a GET Request on the '/movie' route:

$ curl -XGET http://127.0.0.1/movie
forrest gump

This was just a basic example and will be covering more topics in detail at a further stage.

Next up, setting up our Python Environment, with Virtual Environment (virtualenv)

> Tag: Flask-Series