Set a cookie and retrieve it with Python and WSGI
Asked Answered
L

2

5

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

Lydialydian answered 1/1, 2013 at 1:26 Comment(1)
tip: your wsgi apps should return with something like return ["Success"] not return "Success".Tango
T
9

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)
Tango answered 1/1, 2013 at 2:3 Comment(0)
R
3

Here's a simple solution I came up with for setting cookies in WSGI that doesn't require an external library:

def set_cookie_header(name, value, days=365):
    dt = datetime.datetime.now() + datetime.timedelta(days=days)
    fdt = dt.strftime('%a, %d %b %Y %H:%M:%S GMT')
    secs = days * 86400
    return ('Set-Cookie', '{}={}; Expires={}; Max-Age={}; Path=/'.format(name, value, fdt, secs))

def handler(env, start_response):
    content_type = 'text/html'
    headers = [('Content-Type', content_type), set_cookie_header('name', 'value')]
    start_response('200 OK', headers)
    ...
Redletter answered 31/1, 2020 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.