Warm tip: This article is reproduced from stackoverflow.com, please click
ajax cookies python wsgi

Set a cookie and retrieve it with Python and WSGI

发布于 2020-04-08 09:22:09

a lot of questions exists that are similar to this, but none of them helped me out. Basically I'm using WSGI start_response() method link. I tried to set a dummy header in the response with the tuple [('Set-Cookie', 'token=THE_TOKEN')] and add it to start response like this:

status   = '200 OK'
response = 'Success'
start_response(status,[('Set-Cookie', "DMR_TOKEN=DMR_TOKEN")])
return response

I'm not pretty sure that is working correctly, but it's here setting cookies. Now, let's suppose the header is correct and in following requests I want to authenticate a token. What would be the correct way to catch that cookie/header setted in the past ?

I've been reading and find I need something like this:

(environ.get("HTTP_COOKIE",""))

but that has been yielding empty string all the time, so I'm just assuming the header/cookie is not correctly set.

Thanks guys

Questioner
PepperoniPizza
Viewed
64
SingleNegationElimination 2013-01-01 10:03

I think you need to set the path explicitly to get useful behavior out of cookies, try something like:...

from Cookie import SimpleCookie

def my_app(environ, start_response):
    session_cookie = SimpleCookie()
    session_cookie['session'] = "somedata"
    session_cookie['session']["Path"] = '/'

    headers = []
    headers.extend(("set-cookie", morsel.OutputString())
                    for morsel
                    in session_cookie.values())

    start_response("200 OK", headers)