Juan Carlos Coto
Juan Carlos Coto

Reputation: 12574

How to extract particular key from HTTP cookies in Python?

Trying to get a particular value from the cookie string of an HTTP request in Python. I believe possibly using the requests library or urllib2 would be a good idea.

Example:

Assume

headers['cookie'] = 'somekey=somevalue;someotherkey=someothervalue'

Trying to retrieve the value of somekey.

Thanks very much!

Upvotes: 4

Views: 5400

Answers (1)

Chris Dutrow
Chris Dutrow

Reputation: 50372

Cookies can be little %*$%ards. Every time I've tried to use them, there is always some tiny thing I do wrong and they don't work. Best to use a wrapper library.

Using WSGI, you can use the python "cookie" library:

import Cookie

# The function that receives the request
def application(environ, start_response):
    cookie = Cookie.SimpleCookie()
    cookie.load(environ['HTTP_COOKIE'])
    some_value = cookie['some_key'].value

Upvotes: 11

Related Questions