6

Looking at the default "Hello world" script on Flask's website:

from flask import Flask
app = Flask(__name__)

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

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

I'm very new to programming, so I don't understand how this script can work - the hello() function isn't called anywhere, so does Flask simply display the output of the first function found? What if I wanted to display outputs from two or three functions on the page?

  • 2
    Remember also that app.run() calls what is effectively a very simple development web server to run your script, the and app.route("/") decorator works along with the server. So to extend on what Lewis said: Flask has a great deal of code "under the hood" to make the script work, and it's not all visible in the sample script. – abought Oct 03 '12 at 22:22

2 Answers2

10

This line: @app.route("/") will register the function as the handler for the '/' route. When the browser queries '/' (the root), the application responds "Hello World!".

The @ syntax is called Decorators.

How to make a chain of function decorators?

Community
  • 1
  • 1
Lewis Diamond
  • 23,164
  • 2
  • 24
  • 32
1

take a look at this code for instance:

def decorator(func):
    print "this function is called for " + func 
    def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
    return wrapper

@decorator
def hello():
    return "Hello"

Save it into a file and try it,you'll see that after defining hello you see something like this :

this function is called for < function hello at 0x241c70>

slashmili
  • 1,190
  • 13
  • 16