请求会话

时间:2016-11-17 13:24:25

标签: python cookies python-requests

我正在尝试使用机械化浏览器中的cookie来登录请求会话中的站点,但每当我从会话中发出请求时,我都会遇到TypeError。

我已经为使用网站公开的api制作了一个便利类(大多数实际有用的代码被删除了,这只是一个小例子):

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 __future__ import absolute_import, division, print_function, unicode_literals
from requester import Requester

req = Requester(api_root)

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

我从response = method(url)行收到此错误:

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

使用下面的代码测试一个简单的get请求时,生成r1的行有效,但给出r2的行不会

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)

如何正确使用带有requests.Session对象的cookie?

1 个答案:

答案 0 :(得分:1)

您不希望将cookies中单个Cookie的值设置为CookieJar:它已经 一个CookieJar:< / p>

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

您可以通过简单地将s.cookies设置为您的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