Skip to content

Commit 2bb6691

Browse files
committed
update python_requests.py
1 parent 3ea12f7 commit 2bb6691

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

python_requests.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
with open("test", "wb") as fd:
5252
for chunk in r.iter_content(chunk_size=256):
5353
fd.write(chunk)
54+
# 注意: 设置的timeout对connect和read起作用. 但一旦和服务器建立连接, r.content或r.iter_content就处于一个read的状态, 不受timeout影响
5455

5556
# 定制请求头: 一个字典
5657
headers = {"user-agent": "my-app/0.0.1"}
@@ -114,26 +115,26 @@
114115
r = requests.get("http://httpbin.org/cookies", cookies=cookies)
115116
print(r.text)
116117

117-
# 会话对象: 会话对象让你能够跨请求保持某些参数, 它也会在同一个 Session 实例发出的所有请求之间保持cookie
118+
# 会话对象: 会话对象让你能够跨请求保持某些参数, 它也会在同一个Session实例发出的所有请求之间保持cookie
118119
s = requests.Session()
119120
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)
122124

123125
# 会话也可用来为请求方法提供缺省数据, 这是通过为会话对象的属性提供数据来实现的
124-
s = requests.Session()
125126
s.auth = ("user", "pass")
126127
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
128129

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)
137138

138139
# 会话还可以用作前后文管理器
139140
with requests.Session() as s:
@@ -214,3 +215,6 @@ def print_url(resp):
214215
"https": "socks5://user:pass@host:port"
215216
}
216217
requests.get("http://example.org", proxies=proxies)
218+
219+
# 关闭InsecurePlatformWarning
220+
requests.packages.urllib3.disable_warnings()

0 commit comments

Comments
 (0)