Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask : What exactly is @app [duplicate]

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!"
like image 302
Satwik Avatar asked Feb 11 '16 09:02

Satwik


2 Answers

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.

like image 183
Chinmay Kanchi Avatar answered Oct 19 '22 10:10

Chinmay Kanchi


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.

like image 18
JulienD Avatar answered Oct 19 '22 11:10

JulienD