Created
February 8, 2019 02:48
-
-
Save miniyk2012/1ef44c7435a5661dac183cec891de1b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
http://docs.python-requests.org/en/master/user/advanced/#session-objects | |
When your app makes a connection to a server using a Session, | |
it keeps that connection around in a connection pool. | |
When your app wants to connect to the same server again, | |
it will reuse a connection from the pool rather than establishing a new one. | |
""" | |
import requests | |
s = requests.Session() | |
s.auth = ('user', 'pass') # session-level的dict会被session persist | |
s.headers.update({'x-test': 'true'}) # session-level的dict会被session persist | |
# both 'x-test' and 'x-test2' are sent | |
resp = s.get('https://httpbin.org/headers', headers={'x-test2': 'true'}) | |
resp2 = s.get('https://httpbin.org/headers') | |
s.headers['x-test'] = None | |
resp3 = s.get('https://httpbin.org/headers') | |
s.auth = None | |
resp4 = s.get('https://httpbin.org/headers') | |
print(resp.request.headers) | |
print(resp2.request.headers) | |
print(resp3.request.headers) | |
print(resp4.request.headers) | |
s = requests.Session() | |
resp5 = s.get('https://httpbin.org/headers', auth=('yangkai', 'pass')) # method-level的dict不会被session persist | |
print(resp5.request.headers) | |
resp6 = s.get('https://httpbin.org/headers') | |
print(resp6.request.headers) | |
print() | |
with requests.Session() as s: | |
jar = requests.cookies.RequestsCookieJar() | |
jar.set('tasty_cookie', 'yum') | |
s.cookies = jar | |
resp7 = s.get("http://httpbin.org/cookies") | |
s.cookies.clear() | |
resp8 = s.get("http://httpbin.org/cookies") | |
print(resp7.request.headers) | |
print(resp8.request.headers) | |
print(resp7.text) | |
print(resp8.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
输出结果为