Search for '{{search_term}}'

Hello World with Flask and Python

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

In this article we look at the "Hello World" of Flask also shown on the main page of the framework.

examples/flask/hello_world.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

After installing Flask with pip install Flask I could run the above script on the command line using

$ python examples/flask/hello_world.py 

The response was

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Then I turned my browser to the given URL and it indeed showed "Hello World!" while on the console I saw:

127.0.0.1 - - [03/Feb/2015 09:43:14] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [03/Feb/2015 09:43:14] "GET /favicon.ico HTTP/1.1" 404 -

The first one was my reql reuqest, the second one was my browser trying to be nice and trying to fetch the favicon of the site. The first entry ended with HTTP status 200 indicating success, the second request ended with HTTP status 404, indicating "Not found".

The code itself seems to be straight forward.

We declared a function with an arbitrary name (hello), and used the @app.route("/") decorator to map the request to / to this function.

@app.route("/")
def hello():
    return "Hello World!"

When Flask runs, it accepts HTTP request and them maps the requests to routes based on the path in the request. So the above code means if a request comes in for / then run the hello function.

At the end of the script we see this:

if __name__ == "__main__":
    app.run()

The app.run() launches the web server with the Flask-based web application. The if __name__ == "__main__": part protects it so the server will be only launched if the file was executed as a script.

This will allow us to reuse the code in this file as part of another Flask-based application.

(In Perl this kind of behavior is referred to as a Modulino.)

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus