如何使用CherryPy设置多个Cookie

6 投票
1 回答
1935 浏览
提问于 2025-04-17 11:13

根据CherryPy的文档,似乎只有一个cookie的存储位置。下面是我的示例代码:

def sendCookie(self):
    cookie = cherrypy.response.cookie
    cookie['name'] = 'Chips Ahoy!'
    return 'Cookie is now in your hands.'
sendCookie.exposed = True

我想设置多个cookie。我在考虑这样做,但当然这样会覆盖第一个设置。

def sendCookie(self):
    cookie = cherrypy.response.cookie
    cookie2 = cherrypy.response.cookie
    cookie['name'] = 'Chips Ahoy!'
    cookie2['name'] = 'Chocolate Chips'
    return 'Cookie is now in your hands.'
sendCookie.exposed = True

我该如何在CherryPy中设置多个cookie呢?

1 个回答

6

我觉得在cookie中,第一个关键字应该是这个cookie的名字,后面的关键字则是这个cookie的其他属性。所以,和其说用'name'作为cookie的关键字,不如用一个独特的名字。

def sendCookie(self):
    cookies = cherrypy.response.cookie

    cookies['cookie1'] = 'Chips Ahoy!'
    cookies['cookie1']['path'] = '/the/red/bag/'
    cookies['cookie1']['comment'] = 'round'

    cookies['cookie2'] = 'Chocolate Chips'
    cookies['cookie2']['path'] = '/the/yellow/bag/'
    cookies['cookie2']['comment'] = 'thousands'

    return 'Cookies are now in your hands.'
setCookie.exposed = True

这样做可以吗?

补充一下:哎呀,每个morsel都有一套预定义的属性,而我之前定义了自己的属性('shape''count')。现在应该修正过来了。

撰写回答