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

Pel*_*can 7 python cookies http bottle python-3.x

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

  • 检查我们是否识别出用户,
  • 检查语言,
  • 检查位置,
  • 在 html 的导航栏(此处在命名标题之后)中设置变量

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

我发现很难在装饰器中使用 respose.set_cookie("cookie_name", actual_cookie)。似乎flask 有一个运行良好的“make_response”对象(参见堆栈溢出问题34543157:Python Flask - 使用装饰器设置cookie),但我发现很难用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
Run Code Online (Sandbox Code Playgroud)

和路由去的主文件

#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)

Run Code Online (Sandbox Code Playgroud)

我也试过像这样设置cookie:


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

Run Code Online (Sandbox Code Playgroud)

但出现错误:) 这是响应文档:响应文档

你有什么线索吗?谢谢

Tar*_*ani 3

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

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
Run Code Online (Sandbox Code Playgroud)

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

工作正常