开发者

Retrieve a cookie set in Python serverside

G'day, I'm following a guide found here: http://www.doughellmann开发者_StackOverflow中文版.com/PyMOTW/Cookie/

which has the code:

c = Cookie.SimpleCookie()
c.load(HTTP_COOKIE)

to retrieve a cookie previously set (by the server), but my server does not have the HTTP_COOKIE variable, so how else can I do it?

I would prefer to continue using the above guide's method, but if there is something far better I am willing to consider it.

Otherwise, I'm not using any frameworks (just raw .py files) and would like to keep it that way.

Cheers


The way discussed in the comments is:

import os
def getcookies():
    cookiesDict = {}
    if 'HTTP_COOKIE' in os.environ:
        cookies = os.environ['HTTP_COOKIE']
        cookies = cookies.split('; ')
        for cookie in cookies:
            cookie = cookie.split('=')
            cookiesDict[cookie[0]] = cookie[1]
    return cookiesDict

which would then return a dictionary of cookies as key -> value

cookies = getcookies()
userID = cookies['userID']

and obviously you would then add error handling

However there are also other methods, eg., using the cookie module

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜