开发者

Retrieve a cookie set in Python serverside

开发者 https://www.devze.com 2023-04-07 00:18 出处:网络
G\'day, I\'m following a guide found here: http://www.doughellmann开发者_StackOverflow中文版.com/PyMOTW/Cookie/

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

精彩评论

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

关注公众号