【问题标题】:Get status_code with max_retries setting for requests.head使用 requests.head 的 max_retries 设置获取 status_code
【发布时间】: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 我认为我需要:

  • 查看session.mount方法结果是否返回状态码(我还没找到)
  • 推出我自己的重试方法,可能使用像 thisthis 这样的装饰器或像 this 这样的(不太雄辩的)循环。

就我尝试过的第一种方法而言:

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”,我应该查一下这意味着什么。

标签: python python-requests


【解决方案1】:

仅用了两个小时的时间开发了这个问题,答案花了五分钟:

def valid_url(url):
    if (url.lower() == 'none') or (url == ''):
        return False
    try:
        s = requests.Session()
        a = requests.adapters.HTTPAdapter(max_retries=5)
        s.mount(url, a)
        resp = s.head(url)
        return resp.ok
    except requests.exceptions.MissingSchema:
        # If it's missing the schema, run again with schema added
        return valid_url('http://' + url)
    except requests.exceptions.ConnectionError:
        print('Error trying to connect to {}.'.format(url))
        return False

基于this answer,看起来head 请求的资源密集度将略低于get,尤其是在url 包含大量数据的情况下。

requests.adapters.HTTPAdapter 是 Requests 库基础的 urllib3 库的内置适配器。

另一方面,我不确定我在这里检查的正确术语或短语是什么。如果返回错误代码,一个 url 仍然可以是有效的

【讨论】:

  • 这与“我尝试过的第一种方法”有什么不同
  • 第一种方法没有重试。我不断收到一些 301 转发的 URL 的连接错误
  • 我的意思是你所说的我引用的部分。我认为您在写问题时已经回答了这个问题,只是没有将其包含在错误处理中!
  • 唯一的区别是,在解决方案中,我将s.get 替换为s.head,我希望这需要更少的网络活动,但在写完问题之后,我认为值得发布。如果你有时间发表一个更有说服力的答案,我很乐意接受。
猜你喜欢
  • 1970-01-01
  • 2018-07-30
  • 2019-07-16
  • 1970-01-01
  • 2021-07-05
  • 2011-08-10
  • 2023-01-12
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多