會話對象可以跨請求保持某些參數。python
它也會在同一個 Session 實例發出的全部請求之間保持 cookie, 期間使用 urllib3 的 connection pooling 功能。json
因此若是向同一主機發送多個請求,底層的 TCP 鏈接將會被重用,從而帶來顯著的性能提高。服務器
會話對象具備主要的 Requests API 的全部方法。cookie
包含在會話中的數據都能直接使用session
跨請求保持cookie:app
>>> import requests >>> s = requests.session() >>> s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') <Response [200]> >>> r = s.get("http://httpbin.org/cookies") >>> print(r.text) { "cookies": { "sessioncookie": "123456789" } }
會話也可用來爲請求方法提供缺省數據。函數
這是經過爲會話對象的屬性提供數據來實現的:工具
>>> s = requests.session() >>> s.headers.update({'test': 'true'}) >>> s.headers.update({'test1': 'false'}) >>> s.get('http://httpbin.org/headers', headers={'test1': 'true'}) <Response [200]> >>> s.headers {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'test': 'true', 'test1': 'false'}
test和test1的數據都會被髮送性能
任何傳遞給請求方法的字典都會與已設置會話層數據合併,方法層的參數會覆蓋會話的參數。url
方法級別的參數也不會被跨請求保持
>>> s = requests.session() >>> r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'}) >>> print(r.text) { "cookies": { "from-my": "browser" } } >>> r = s.get('http://httpbin.org/cookies') >>> print(r.text) { "cookies": {} }
獲取的cookie是第一個不是第二個
若是要手動爲會話添加 cookie,就使用 Cookie utility 函數 來操縱 Session.cookies
會話還能夠用做先後文管理器:
>>> with requests.session() as s: ... s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') ... <Response [200]>
這樣就能確保with區塊退出後會話能被關閉,即便發生了異常也同樣。
若是要省略字典參數中一些會話層的鍵。只需在方法層參數中將那個鍵的值設置爲None ,那個鍵就會被自動省略掉。
>>> r = requests.get('http://httpbin.org/get') >>> r.headers #服務器返回的響應頭部信息 {'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Fri, 09 Feb 2018 13:09:33 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000726938247681', 'Content-Length': '265', 'Via': '1.1 vegur'} >>> r.request.headers #發送到服務器的請求的頭部信息 {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
SSL驗證默認是開啓的,若是證書驗證失敗,requests會拋出SSLError的錯誤
能夠經過verify參數來解決
給verify傳入CA_BUNDLE文件的路徑,或者包含可信任CA證書文件的文件夾路徑
>>> requests.get('https://httpbin.org/get', verify='/path/to/certfile')
也能夠把證書包含在會話中
s = requests.session() s.verify = '/path/to/certfile'
若是verify設爲文件夾路徑,文件夾必須經過OpenSSL提供的c_rehash工具處理
還能夠經過REQUESTS_CA_BUNDLE環境變量定義可信任CA列表
verify參數僅用於主機證書,對於私有證書,能夠傳遞一個 CA_BUNDLE 文件的路徑給verify,也能夠設置REQUEST_CA_BUNDLE環境變量
verify的默認值爲True,也能夠將verify設置爲False,requests就會忽略對SSL證書的驗證
>>> requests.get('https://www.baidu.com/', verify=False) <Response [200]>