4
votes

Suppose there is a view of the function is as follows:

@app.route('/cat/', methods=('GET', 'POST'))
@check_something(check='cat')
def cat():
    print 'cat'
    return 'cat'

@app.route('/dog/', methods=('GET', 'POST'))
@check_something(check='dog')
def dog():
    print 'dog'
    return 'dog'

Here, I used a decorator named check_something(), what i want to do is to check the condition before execute mainfanction. The decorator function code is :

def check_something(check=''):
    def decorator(f):
        @functools.wraps(f)
        def decorated_function(*args, **kwargs):
            print('check_start')
            if check == 'dog':
                return jsonify( ret='check dog' )
            else:
                ctx = f(*args, **kwargs)
                return jsonify( ret=ctx )
        return decorated_function
    return decoration

I test it from android client and web client, below are the test results:

Android + GET: route 'cat' is OK, route 'dog' is OK;
Web + GET    : route 'cat' is OK, route 'dog' is OK;
Android +POST: route 'cat' is OK, route 'dog' is Failed, raise SocketTimeoutException;
Web + POST: i didn't test it.

Why? It's so strange!

Let me talk about some personal speculation.

1.It is caused by the decorator.*Flask's decorator @app.route() wil record the decorated function. And so I added functools.wraps(f) for keep function's feature. But when program execute check_something(check='dog'), it didn't execute f(*args, **kwargs), so flask lose the decorated function's feature. And so flask lose response. I guess.

2.But why the GET can execute success? Maybe there have some problem between Flask and POST. I guess, too.

Can anyone give me some help? Thanks!

1
Just tried both GET + POST (web), worked fine. One thing, in the check_something function, the most outer return should be returning decorator instead of decoration. - jbub
I do not see you checking for the request method. ("methods" only specifies the allowed methods) flask.pocoo.org/docs/0.10/quickstart/#http-methods - Maarten

1 Answers

0
votes

I think there is an error in your decorator. f is the function being decorated and if there is a test f is not being executed. a corrected version:

 print('check_start')
 if check == 'dog':
      ctx = f(*args, **kwargs)
      return jsonify( ret='check dog' )
 else:
      ctx = f(*args, **kwargs)
      return jsonify( ret=ctx