【问题标题】:How to pass a retry strategy to a session in python requests如何在 python 请求中将重试策略传递给会话
【发布时间】:2022-11-10 09:41:16
【问题描述】:

我正在使用 requests 包从网页中获取数据。我在教程后创建了重试策略,但我不明白如何将其提供给会话。

retry_strategy = Retry(total=10,
                       backoff_factor=5,
                       status_forcelist=[429, 500, 501, 502, 503],
                       allowed_methods=["GET"])
adapter = HTTPAdapter(max_retries=retry_strategy)

如果我尝试通过它,我会得到:

session = requests.Session(adapter)
TypeError: Session.__init__() takes 1 positional argument but 2 were given

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    您已经做对了所有事情,但是您不需要传递适配器,而是需要使用 .mount() 方法,如下所示:

    session = requests.Session()
    session.mount("https://", adapter)
    

    【讨论】:

    • 您还可以提及,session 初始化。
    • @莎拉:很高兴它有效。 @Rahul K P:谢谢,我已将其添加到我的答案中。
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2018-08-12
    • 2021-03-25
    • 2020-10-23
    • 1970-01-01
    • 2018-09-20
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多