Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cookie and retrieve it with Python and WSGI

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

like image 947
PepperoniPizza Avatar asked Jan 01 '13 01:01

PepperoniPizza


2 Answers

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)
like image 64
SingleNegationElimination Avatar answered Nov 14 '22 21:11

SingleNegationElimination


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)
    ...
like image 27
Steven Moseley Avatar answered Nov 14 '22 22:11

Steven Moseley