I am following this Flask tutorial. We declare routes like @app.route('/') , but no variable in python can contain @ character.
I'm confused that what is @app and where it came from. Here's the code snippet :
from app import app
@app.route('/')
@app.route('/index')
def index():
return "Hello, World!"
The @ is telling Python to decorate the function index() with the decorator defined in app.route().
Basically, a decorator is a function that modifies the behaviour of another function. As a toy example, consider this.
def square(func):
def inner(x):
return func(x) ** 2
return inner
@square
def dbl(x):
return x * 2
Now - calling dbl(10) will return not 20, as you'd expect but 400 (20**2) instead.
This is a nice step-by-step. explanation of decorators.
It is a decorator. When decorated by @app.route('/') (which is a function), calling index() becomes the same as calling app.route('/')(index)().
Here is another link that can explain it, in the python wiki.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With