首页 > 解决方案 > python cookie的奇怪行为,无法设置cookie

问题描述

我使用 Python Nameko 作为我的微服务框架,当我尝试在我的 get 请求中设置 cookie 时,我似乎做不到,下面是我的代码:

from http import cookies
from nameko.web.handlers import http

@http('GET', '/hello')
    def say_hello(self, request):
        c = cookies.SimpleCookie()
        c['test-cookie'] = 'test-1'
        return 200, c, 'Hello World!'

当我使用 Postman 调用获取请求时,以下是我从请求中返回的内容: 在此处输入图像描述

任何人都可以帮助理解这种行为吗?如图所示,它不是 Set-Cookie ->,而是 ->。谢谢你。

标签: pythoncookieshttp-headerssetcookienameko

解决方案


根据文档,三元组响应类型nameko.http(status_code, headers dict, response body)。也就是第二个参数是headers的dict,和cookie对象不一样

要设置 cookie,您需要构建werkzeug.wrappers.Response自己的实例(也包含在文档中的该列表中):

    @http('GET', '/hello')
    def say_hello(self, request):
        response = Response("Hello World!")
        response.set_cookie('test-cookie', 'test-1')
        return response

推荐阅读