1

我正在尝试使用requests.Session来发出一些请求,并且我希望不设置 cookie。看看这个问题,看来我可以创建一个 cookie 策略,并根据该策略创建一个 cookie jar 以忽略 cookie。但是,对于我的请求,似乎仍然设置了 cookie:

from http import cookiejar

class BlockAll(cookiejar.CookiePolicy):
        """ Blocks all cookies for a given request.
        """
        return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
        netscape = True
        rfc2965 = hide_cookie2 = False


def get_cookie_jar():
    cookies = cookiejar.CookieJar(policy=BlockAll())
    return cookies

session = requests.Session()
response = session.request(
   method='post',
   url='some_url.com',
   cookies=get_cookie_jar(),
   ....
)

print(response.cookies)
<RequestsCookieJar[Cookie(version=0, name='JSESSIONID', value='1234', port=None, port_specified=False, domain='some_url.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>

这是为此类请求设置策略的正确方法吗?任何相关文档的帮助/链接将不胜感激。

4

1 回答 1

2

cookies参数request(...)允许您在请求中指定传出cookie响应中的传入 cookie 不会被咨询。

您需要在会话上设置策略:

session = requests.Session()
session.cookies.set_policy(BlockAll())

演示:

>>> session = requests.Session()
>>> response = session.request('GET', 'http://httpbin.org/cookies/set?foo=bar')
>>> session.cookies  # no policy, so cookie got set
<RequestsCookieJar[Cookie(version=0, name='foo', value='bar', port=None, port_specified=False, domain='httpbin.org', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>
>>> session.cookies.clear()  # clean slate, no cookies
>>> session.cookies
<RequestsCookieJar[]>
>>> session.cookies.set_policy(BlockAll())
>>> response = session.request('GET', 'http://httpbin.org/cookies/set?foo=bar')
>>> session.cookies  # with policy, cookies still empty
<RequestsCookieJar[]>
于 2017-10-16T19:02:42.517 回答