问题
I'm trying to write a decorator that checks for a cookie, and sets one if it doesn't exist. This is my desperate attempt to get the idea across.
def set_cookie(f):
def decorated_function(*args, **kws):
if 'cstc' in flask.request.cookies.keys():
return make_response(f).set_cookie('cstc', value='value')
else:
return f
return decorated_function
@main.route('/home')
@set_cookie
def home():
return render_template('main/home.html')
Right now I'm getting error:
TypeError: home() takes no arguments (2 given)
回答1:
You have to call the original function:
def set_cookie(f):
def decorated_function(*args, **kws):
response = f(*args, **kws)
response = make_response(response)
if 'cstc' in flask.request.cookies.keys():
response.set_cookie('cstc', value='value')
return response
return decorated_function
回答2:
Your decorator should look something like this:
from functools import wraps
def set_cookie(f):
@wraps(f)
def decorated_function(*args, **kws):
#your code here
return f(*args, **kws)
return decorated_function
You can also have a look at the official flask documentation: http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/
回答3:
from functools import wraps
def set_cookie(f):
@wraps(f)
def decorated_function(*args, **kws):
#your code here
return f(*args, **kws)
return decorated_function
来源:https://stackoverflow.com/questions/34543157/python-flask-setting-a-cookie-using-a-decorator