0

I'm new to Flask. When I came across basic Flask example(below code), I stuck with the uncertainty: what is the need to use @ before variable app. I tried running app while removing @, but I can't. If it is some very basic thing that I'm asking about, please comment.

from flask import Flask, escape, request

app = Flask(__name__)

@app.route('/')

def hello():
   name = request.args.get("name", "World")
   return f'Hello, {escape(name)}!'
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
SriDatta Yalla
  • 766
  • 8
  • 13

3 Answers3

2

The @ symbol is used for decorators.

A decorator is a function that takes another function as argument, and modifies its behavior.

In the case of Flask, app.route is a decorator that will "install" your function as the handler for a speficif route in your web app.

Doing this:

@app.route('/foo')
def hello():
    return 'Hello'

is the same as doing:

def f():
    return 'Hello'

decorator = app.route('/foo')
hello = decorator(f)

What the @ symbol does is implicitly calling the result of app.route('/foo') with your function as argument. As you can see this makes the above code more convenient and easy to read.


If you look at the Flask source code, you'll see the definition of route() as a method of the class Flask:

class Flask:
    #...
    def route(self, rule, **options):
        def decorator(f):
            endpoint = options.pop("endpoint", None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f

        return decorator
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
1

That's a decorator. In short route is decorator that tell Flask what URL should trigger our function.

Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
1

Python decorators are functions that are used to transform other functions. When a decorated function is called, the decorator is called instead. The decorator can then take action, modify the arguments, halt execution or call the original function. We can use decorators to wrap views with code we’d like to run before they are executed.

@decorator_function
def decorated():
    pass

If you’ve gone through the Flask tutorial, the syntax in this code block might look familiar to you.

@app.route is a decorator used to match URLs to view functions in Flask apps.

For more detailed description, you can even refer to this documentation Also, there is a similar question asked on the stackoverflow, you can refer to this as well.

Jaldhi Mehta
  • 711
  • 6
  • 10