-2

The following code (pseudocode) in flask confused me a lot.

def IsIllegal(f):
    @wraps(f)
    def decorated(*args,**kwargs):
        if True:
            return error msg
        else:
            return f(*args,**kwargs)
    return decorated

@IsIllegal
@app.route(...,  methods = ['POST']  )
def func1():
    data = flask.request.get_data()
    print(data)
    ...

where function IsIllegal is used to check if the user is NOT logged in. What I found is that func1 always print the data even the user is not logged in. The return value of func1 is, as expected, stopped by the function IsIllegal. But I feel that it is not save because the statement in func1 is executed (the print). How can I understand this?

hengyue li
  • 448
  • 3
  • 17

1 Answers1

0

You registered the undecorated func1() function. The @IsIllegal() decorator result is applied after registration by the @app.route() decorator, and is never called when the route is accessed.

Decorators are applied in reverse order, from the inside out, so to speak. Reverse the decorators:

@app.route(...,  methods = ['POST']  )
@IsIllegal
def func1():

Now the result of IsIllegal(func1) is registered by @app.route(...), so accessing the route will end up calling decorated().

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343