How to write Flask decorator with request?
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.
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..