You need to enable JavaScript to run this app. 如何修改Python请求脚本,实现请求超时10秒自动重试?
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python请求脚本,实现请求超时10秒自动重试?

解决方案

我们可以利用requests库的timeout参数直接设置请求超时阈值,同时捕获超时异常,将状态码非200和请求超时两种情况都作为重试触发条件。修改后的代码如下:

import requests
from requests.exceptions import Timeout

# Defining Functions to use in the script
def make_request(student_id):
    """
    Makes a response for the student ID given, Keeps repeating it till it's a successful response.
    """
    url = 'http://app1.helwan.edu.eg/Commerce/HasasnUpMlist.asp' # Base URL to our college website

    params = {
        'z_dep': '=',
        'z_st_name': 'LIKE',
        'z_st_settingno': '=',
        'x_st_settingno': f'{student_id}',
        'x_st_name': '',
        'z_gro': '=',
        'x_gro': '',
        'x_dep': '',
        'z_sec': 'LIKE',
        'x_sec': '',
        'Submit': '++++حفظ++++'
    }

    while True:
        try:
            # 设置10秒超时,超过时限则抛出Timeout异常
            response = requests.get(url, params=params, timeout=10)
            # 状态码为200时返回响应,否则继续重试
            if response.status_code == 200:
                return response
        except Timeout:
            # 捕获超时异常,直接进入下一次循环重试
            continue

关键修改说明

  • 给requests.get()添加timeout=10参数,让请求在10秒内未得到响应时自动触发超时异常
  • 用while True循环统一处理两种重试场景,替代原有的单一状态码判断逻辑
  • 捕获requests.exceptions.Timeout异常,遇到超时直接重试
  • 仅当请求成功返回200状态码时,才退出循环并返回响应

内容的提问来源于stack exchange,提问作者Esmael Maher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:10:30