2012-01-27 81 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