|
51 | 51 | with open("test", "wb") as fd: |
52 | 52 | for chunk in r.iter_content(chunk_size=256): |
53 | 53 | fd.write(chunk) |
| 54 | +# 注意: 设置的timeout对connect和read起作用. 但一旦和服务器建立连接, r.content或r.iter_content就处于一个read的状态, 不受timeout影响 |
54 | 55 |
|
55 | 56 | # 定制请求头: 一个字典 |
56 | 57 | headers = {"user-agent": "my-app/0.0.1"} |
|
114 | 115 | r = requests.get("http://httpbin.org/cookies", cookies=cookies) |
115 | 116 | print(r.text) |
116 | 117 |
|
117 | | -# 会话对象: 会话对象让你能够跨请求保持某些参数, 它也会在同一个 Session 实例发出的所有请求之间保持cookie |
| 118 | +# 会话对象: 会话对象让你能够跨请求保持某些参数, 它也会在同一个Session实例发出的所有请求之间保持cookie |
118 | 119 | s = requests.Session() |
119 | 120 | s.get("http://httpbin.org/cookies/set/sessioncookie/123456789") |
120 | | -r = s.get("http://httpbin.org/cookies") |
121 | | -print(r.text) # '{"cookies": {"sessioncookie": "123456789"}}' |
| 121 | +s.get("http://httpbin.org/cookies") |
| 122 | +for cookie in s.cookies: |
| 123 | + print(cookie) |
122 | 124 |
|
123 | 125 | # 会话也可用来为请求方法提供缺省数据, 这是通过为会话对象的属性提供数据来实现的 |
124 | | -s = requests.Session() |
125 | 126 | s.auth = ("user", "pass") |
126 | 127 | s.headers.update({"x-test": "true"}) |
127 | | -s.get("http://httpbin.org/headers", headers={"x-test2": "true"}) # both "x-test" and "x-test2" are sent |
| 128 | +s.get("http://httpbin.org/headers", headers={"x-test2": "true"}) # both "x-test" and "x-test2" are sent |
128 | 129 |
|
129 | | -# 不过需要注意, 就算使用了会话, 方法级别的参数也不会被跨请求保持 |
130 | | -# 下面的例子只会和第一个请求发送cookie, 而非第二个 |
131 | | -s = requests.Session() |
132 | | -r = s.get("http://httpbin.org/cookies", cookies={"from-my": "browser"}) |
133 | | -print(r.text) # '{"cookies": {"from-my": "browser"}}' |
134 | | -r = s.get("http://httpbin.org/cookies") |
135 | | -print(r.text) # '{"cookies": {}}' |
136 | | -# 如果你要手动为会话添加 cookie, 就是用 Cookie utility 函数来操纵Session.cookies |
| 130 | +# 不过需要注意, 就算使用了会话, 方法级别的参数也不会被跨请求保持, 下面的例子只会给第一个请求发送cookie |
| 131 | +s.get("http://httpbin.org/cookies", cookies={"from-my": "browser"}) # 带有cookie |
| 132 | +s.get("http://httpbin.org/cookies") # 不带cookie |
| 133 | + |
| 134 | +# 如果你要手动为会话添加cookie, 就是用Cookie utility函数来操纵Session.cookies |
| 135 | +requests.utils.add_dict_to_cookiejar(s.cookies, {"cookie_key": "cookie_value"}) |
| 136 | +for cookie in s.cookies: |
| 137 | + print(cookie) |
137 | 138 |
|
138 | 139 | # 会话还可以用作前后文管理器 |
139 | 140 | with requests.Session() as s: |
@@ -214,3 +215,6 @@ def print_url(resp): |
214 | 215 | "https": "socks5://user:pass@host:port" |
215 | 216 | } |
216 | 217 | requests.get("http://example.org", proxies=proxies) |
| 218 | + |
| 219 | +# 关闭InsecurePlatformWarning |
| 220 | +requests.packages.urllib3.disable_warnings() |
0 commit comments