如何使用CherryPy设置多个cookie

时间:2012-01-27 13:35:31

标签: python cookies cherrypy

从CherryPy documentation,似乎只有一个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 个答案:

答案 0 :(得分:5)

我认为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')。现在应该修好。