Python Decorator Self-firing

I am new to Python and learned about decorators. After messing with Flask, I try to write code that mimics their route handler / decorators, just to understand how decorators (with arguments) work.

In the code below, the route decorator seems to call itself after running the script. My question is, how is it possible that app.route()gets called when I run this script, and what actually happens here? Note that I do not call the function index()anywhere directly.

# test.py

class Flask(object):

    def __init__(self, name):
        self.scriptname = name

    def route(self, *rargs, **kargs):
        args = list(rargs)
        if kargs:
            print(kargs['methods'])
        def decorator(f):
            f(args[0])
        return decorator

app = Flask(__name__)

@app.route("/", methods = ["GET","PUT"])
def index(rt):
    print('route: ' + rt)

the above produces this in my terminal:

$ python test.py
['GET', 'PUT']
route: /

Any insight would be appreciated.

0
source share
2 answers

@app.route("/", methods = ["GET","PUT"]) - : route() . , , script.

app.route(...) - , @, , index. , :

index = app.route(...)(index)

, Python , app.route() index , index.

, . , , :

@foo
def bar()
   pass

, foo() , bar. route() ! , , , ... headscratching, .

route :

def route(self, *rargs, **kargs):
    args = list(rargs)
    if kargs:
        print(kargs['methods'])
    def decorator(f):
        def wrapped(index_args):
            f(args[0])
        return wrapped
    return decorator
+2

... app.route(index, "/", ["GET", "PUT"]) - . , .

, index(), app.route(index, "/", ["GET", "PUT"]). kargs['methods'], :

def decorator(f):
    f(args[0])

(f) args[0], "/". route: /.

, , : ?

, :

def route(*rargs, **kargs):
    args = list(rargs)
    if kargs:
        print(kargs['methods'])
    def decorator(f):
        f(args[0])
    return decorator

@app.route("/", methods = ["GET","PUT"])
def index(rt):
    print('route: ' + rt)

rt , route index args[0], \...

-1

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


All Articles