我正在尝试编写一个检查cookie的装饰器,如果它不存在则设置一个。这是我绝望的尝试,以实现这个想法。
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')
现在我收到错误:
TypeError: home() takes no arguments (2 given)
答案 0 :(得分:2)
您必须调用原始函数:
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
答案 1 :(得分:1)
你的装饰师应该是这样的:
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
您还可以查看官方烧瓶文档:http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/
答案 2 :(得分:-1)
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