創建session object,這是advanced usage下所示的第1件事:
,並使用會話執行請求。正如你說,你不希望在請求之間持續存在的cookie,你可以繼承的Session
:
In [64]: from requests.adapters import HTTPAdapter
In [65]: from requests.cookies import cookiejar_from_dict
In [66]: class CookieMonsterSession(Session):
...:
...: def __init__(self, *args, **kwgs):
...: super(CookieMonsterSession, self).__init__(*args, **kwgs)
...: # Override default adapters with 0-pooling adapters
...: self.mount('https://', HTTPAdapter(pool_connections=1,
...: pool_maxsize=0))
...: self.mount('http://', HTTPAdapter(pool_connections=1,
...: pool_maxsize=0))
...: @property
...: def cookies(self):
...: """ Freshly baked cookies, always!"""
...: return cookiejar_from_dict({})
...: @cookies.setter
...: def cookies(self, newcookies):
...: """ OM NOM NOM NOM..."""
...: pass
...:
In [67]: s = CookieMonsterSession()
In [69]: real_s = Session()
In [70]: s.get('http://www.google.fi')
Out[70]: <Response [200]>
In [71]: s.cookies
Out[71]: <RequestsCookieJar[]>
In [72]: real_s.get('http://www.google.fi')
Out[72]: <Response [200]>
In [73]: real_s.cookies
Out[73]: <RequestsCookieJar[Cookie(version=0, name='NID', value='86=14qy...Rurx', port=None, port_specified=False, domain='.google.fi', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1489744358, discard=False, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
不幸的是,Session
是由設計難以擴展和配置,所以「禁用」餅乾,並修改像這樣的池是一個破解,並容易打破,如果當Session
更新絲毫。此外,我們僅針對持久性標頭禁用了Session
的2個主要功能。
結束語基本API方法可能是更清潔和更安全的方法:
# customrequests.py
from functools import wraps
from requests import api as requests_api
custom_headers = {}
def _header_wrapper(f):
@wraps(f)
def wrapper(*args, **kwgs):
headers = kwgs.pop('headers', None) or {}
headers.update(custom_headers)
return f(*args, headers=headers, **kwgs)
return wrapper
request = _header_wrapper(requests_api.request)
get = _header_wrapper(requests_api.get)
options = _header_wrapper(requests_api.options)
head = _header_wrapper(requests_api.head)
post = _header_wrapper(requests_api.post)
put = _header_wrapper(requests_api.put)
patch = _header_wrapper(requests_api.patch)
delete = _header_wrapper(requests_api.delete)
在行動:
In [1]: import customrequests as requests
In [2]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1"
}
}
In [3]: requests.custom_headers['X-Test'] = "I'm always here"
In [4]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1",
"X-Test": "I'm always here"
}
}
想過這個問題,但是:它存儲的cookie,我不想和還會保持連接打開狀態,這可能會在整個應用生命週期中產生問題。 – Baczek
如果這是一個問題,我會建議與你最初的包裝想法。如果您的代碼正在使用或不在使用中,那麼在查看代碼時就會很明顯。 –