smernst
smernst

Reputation: 184

TypeError for cookielib CookieJar cookie in requests Session

I'm trying to use a cookie from a mechanize browser that I use to log in to a site in a requests Session, but whenever I make a request from the session I get a TypeError.

I've made a convenience class for using an api exposed by the site (most of the actually useful code is removed, this is a small example):

from __future__ import absolute_import, division, print_function, unicode_literals
import requests
import mechanize
import cookielib

class Requester:
    def __init__(self, api_root_url):
        self.api_root_url = api_root_url
        self.s = requests.Session()
        self.new_cookie()

    def new_cookie(self):
        br = mechanize.Browser()
        cookie_jar = cookielib.CookieJar()
        br.set_cookiejar(cookie_jar)

        # Acquire cookies by logging in with mechanize browser

        self.s.cookies.set('v_cookies', cookie_jar)

    def make_request(self, req_method, endpoint):
        url = self.api_root_url + endpoint
        method = getattr(self.s, method)
        response = method(url)
        return response

From another script I use this class to make requests like this:

from __future__ import absolute_import, division, print_function, unicode_literals
from requester import Requester

req = Requester(api_root)

response = req.make_request('get', endpoint)

And I get this error from the response = method(url) line:

File "...\Anaconda2\lib\cookielib.py", line 1301, in _cookie_attrs
    self.non_word_re.search(cookie.value) and version > 0):
TypeError: expected string or buffer

When testing a simple get request with the code below, the line producing r1 works but the line giving r2 does not

def make_request(self, req_method, endpoint):
    url = self.api_root_url + endpoint
    cookies = self.s.cookies.get('v_cookies')
    r1 = requests.get(url, cookies=cookies)
    r2 = self.s.get(url)

How do I correctly use cookies with a requests.Session object?

Upvotes: 1

Views: 513

Answers (1)

Lukasa
Lukasa

Reputation: 15518

You don't want to set the value of a single cookie in cookies to a CookieJar: it already is a CookieJar:

>>> s = requests.Session()
>>> type(s.cookies)
<class 'requests.cookies.RequestsCookieJar'>

You'll probably have a better time by simply setting s.cookies to your cookiejar:

def new_cookie(self):
    br = mechanize.Browser()
    cookie_jar = cookielib.CookieJar()
    br.set_cookiejar(cookie_jar)

    # Acquire cookies by logging in with mechanize browser

    self.s.cookies = cookie_jar

Upvotes: 1

Related Questions