Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 471
Juan Carlos Coto Avatar asked Dec 27 '22 02:12

Juan Carlos Coto


1 Answers

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
like image 106
Chris Dutrow Avatar answered Dec 31 '22 12:12

Chris Dutrow