In Flask, why does this hello world application work?

See the default "Hello world" script on the Flask website:

from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() 

I am very new to programming, so I don’t understand how this script can work - the hello() function is not called anywhere, so does Flask just display the output of the first function found? What if I want to display output from two or three functions on a page?

+6
source share
2 answers

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

The @ syntax is called Decorators.

How to create a chain of function decorators?

+10
source

take a look at this code, for example:

 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 to a file and try, you will see that after defining the greeting, you see something like this:

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

+1
source

Source: https://habr.com/ru/post/926881/


All Articles