Bart
Bart

Reputation: 543

Python Requests cookies of a specific request within the session

I'm trying to find a way to extract and optionally delete cookies sent by a specific request, instead of checking the session cookie jar.

The Requests library stores cookies of all the requests, and I'm having trouble accessing cookies sent by a request the program is currently working at.

Example code of deleting a session cookie:

import requests


s = requests.Session()
r = s.get('http://httpbin.org/cookies/set', params={'foo': 'bar', 'key2': 'value2'})
print('Before Clear:')
print(s.cookies.items())
>>[('foo', 'bar'), ('key2', 'value2')]

s.cookies.clear(domain='httpbin.org', path='/', name='foo')

print('After Clear:')
print(s.cookies.items())
>>[('key2', 'value2')]

Now, because this is a session, I can't seem to be able to access the cookies of a specific request, like:

r.cookies['foo']

The reason why I need cookies of a specific request is because I'm using requests-futures, so when the application is working on a request X, I have other requests working simultaneously, writing to the session cookiejar.

What seems like something I could use is the extract_cookies API call.

By the way, how to use the Requests API in requests-futures? For example:

requests.utils.add_dict_to_cookiejar(cj, cookie_dict)

Here's the requests-futures short source code.

Thank you!

Upvotes: 1

Views: 3936

Answers (1)

ashwinjv
ashwinjv

Reputation: 2967

You could have a function that builds a request with only the cookies you need from the session and send that request.

Note: This second request does not update your session variables. So if you set another cookie using the second request, your session cookies are not updated

import requests

def generateCookie(keys, session):
    cookie = {}
    for k, v in session.cookies.get_dict().items():
        if k in keys:
            cookie[k] = v
    return cookie


s = requests.Session()
r = s.get('http://httpbin.org/cookies/set', params = {'foo': 'bar', 'key': 'value', 'Larry': 'Moe'})

print('Session Cookies:', s.cookies.items())

p = requests.get('http://httpbin.org/cookies', cookies=generateCookie(['foo', 'Larry'], s))

print(p.text)

print('Session Cookies:', s.cookies.items())


###########
# OUTPUT
###########
Session Cookies: [('Larry', 'Moe'), ('foo', 'bar'), ('key', 'value')]
{
  "cookies": {
    "Larry": "Moe", 
    "foo": "bar"
  }
}

Session Cookies: [('Larry', 'Moe'), ('foo', 'bar'), ('key', 'value')]

Upvotes: 1

Related Questions