Python Flask - Setting a cookie using a decorator

狂风中的少年 提交于 2020-06-27 13:12:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!