python - How to write Flask decorator with request?

ID : 274549

viewed : 33

Tags : pythonflaskpython-decoratorspython





Top 3 Answer for python - How to write Flask decorator with request?

vote vote

92

This is how your decorator should look like

def validate_request(f):   @functools.wraps(f)   def decorated_function(*args, **kwargs):     # Do something with your request here     data = flask.request.get_json()     if not data:       flask.abort(404)     return f(*args, **kwargs)   return decorated_function 

and you will call it like this

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT']) @validate_request def update_task(task_id):     # The rest of your code.. 
vote vote

86

It's kind of an old post, but I think that it may benefit from a little correction: decorated_function needs to return f(*args, **kws)

def validate_request(f):   @functools.wraps(f)   def decorated_function(*args, **kws):     # Do something with your request here     data = flask.request.get_json()     if not data:       flask.abort(404)     return f(*args, **kws)   return decorated_function 

Otherwise you will encounter TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

vote vote

80

Top 3 video Explaining python - How to write Flask decorator with request?







Related QUESTION?