2012-01-27 51 views
5

从CherryPy documentation,似乎只有一个Cookie插槽。这里是我的示例代码如何使用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?

回答

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')。现在应该修复。

+0

不,只有一个cookie被设置。在这种情况下,只有'cookie2'。 'cookie1'无处可寻。 – Kit 2012-01-27 17:06:38

+0

抱歉。都很好。我正在测试一个不安全的http,并将我的第一个cookie设置为'secure' :) – Kit 2012-01-27 17:08:26

+0

嗯,好的。根据[这个页面](http://blog.eddsn.com/2010/05/how-to-use-cookies-with-cherrypy/),你需要发送''max-age''或'expires' '也为每个cookie。如果这不起作用,恐怕我没有想法。 :/ – aganders3 2012-01-27 17:11:54