Python Flask-使用装饰器设置Cookie [英] Python Flask - Setting a cookie using a decorator
本文介绍了Python Flask-使用装饰器设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个装饰器,该装饰器检查cookie,并设置一个cookie(如果不存在)。这是我拼命尝试的想法。
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')
现在我出错了:
TypeError: home() takes no arguments (2 given)
推荐答案
您必须调用原始函数:
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
这篇关于Python Flask-使用装饰器设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文