【发布时间】:2019-03-12 16:59:32
【问题描述】:
如here 所见,max-retries 可以设置为requests.Session(),但我只需要head.status_code 来检查网址是否有效且处于活动状态。
有没有办法在挂载会话中获取头部?
import requests
def valid_active_url(url):
try:
site_ping = requests.head(url, allow_redirects=True)
except requests.exceptions.ConnectionError:
print('Error trying to connect to {}.'.format(url))
try:
if (site_ping.status_code < 400):
return True
else:
return False
except Exception:
return False
return False
基于docs 我认为我需要:
就我尝试过的第一种方法而言:
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=3)
s.mount('http://redirected-domain.com', a)
resp = s.get('http://www.redirected-domain.org')
resp.status_code
我们是否只使用s.mount() 进入并设置max_retries?似乎是一种冗余,除了 http 连接将被预先建立。
还有 resp.status_code 返回 200 我期待 301 (这是 requests.head 返回的内容。
注意:resp.ok 可能是我在这里的目的所需要的。
【问题讨论】:
-
.mount没有提出请求。 “挂载调用将传输适配器的特定实例注册到前缀。一旦挂载,使用 URL 以给定前缀开头的会话发出的任何 HTTP 请求都将使用给定的传输适配器。”跨度> -
是的。我想,与其让我的眼睛盯着“Transport Adapter to a prefix”,我应该查一下这意味着什么。