gpt4 book ai didi

python - Cookie 政策被忽略?

转载 作者:行者123 更新时间:2023-12-01 02:31:26 24 4
gpt4 key购买 nike

我正在尝试使用 requests.Session提出一些请求,但我不希望设置 cookie。正在查看this question ,看来我可以创建一个 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)]>

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

最佳答案

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

您需要在 session 上设置策略:

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[]>

关于python - Cookie 政策被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46777164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com