bottle :如何在 python 装饰器中设置 cookie?

bottle : how to set a cookie inside a python decorator?

在运行设置一些路由之前需要完成一些操作。例如:

依此类推,然后根据结果做出决定,最后运行请求的路线。

我发现很难在装饰器中使用 respose.set_cookie("cookie_name", actual_cookie) 。似乎 flask 有一个 "make_response" object 效果很好(请参阅堆栈溢出问题 34543157:Python Flask - Setting a cookie using a decorator),但我发现很难用 bottle 重现相同的东西。

我的尝试是怎么行不通的:

#python3
#/decorator_cookie.py

from bottle import request, response, redirect

from other_module import datamodel, db_pointer, secret_value #custom_module

import json

cookie_value = None
surfer_email_exist_in_db = None 
header = None 
db_pointer = instanciation_of_a_db_connexion_to_tables
surfer = db_pointer.get(request.get_cookie('surfer')) if  db_pointer.get(request.get_cookie('surfer')) != None else "empty"

def set_header(func):
    def header_manager():

        global cookie_value, surfer_email_exist_in_db, header, db_pointer                                                                                                                                   
        cookie_value = True #for stack-overflow question convenience
        surfer_email_exist_in_db = True #for stack-overflow question convenience

        if not all([cookie_value, surfer_email_exist_in_db]):
            redirect('/login')

        else:
            header = json.dumps(db_pointer.get('header_fr'))

            response.set_cookie("header", header, secret = secret_value, path = "/", httponly = True)

           return func()
    return header_manager

以及路由到的主文件

#python3
#/main.py

from bottle import route, request
from decorator_cookie import set_header
from other_module secret_value

@route('/lets_try')
@set_header
def lets_try():

    header = request.get_cookie('header', secret = secret_value)
    print(header) #here I get None
    return template('lets_try.tpl', headers = header)

我也试过这样设置 cookie :


make_response = response(func).set_cookie("header", header, secret = secret_value, path = "/", httponly = True)

但是出错了:) 这是响应文档:Response documentation

你有什么线索吗? 谢谢

你的代码没有问题,你缺的是理解就是理解

Request 1 [By Browser/No Cookies] -> Request has No cookies -> Response you add cookie header

Request 2 [By Browser/Header Cookies] -> Request has Header cookies -> Response

因此,对于您的第一个请求,Request.get_cookie 将 return None 但对于您的第二个请求,它实际上将 return 值