微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:即使互联网关闭,响应代码也会返回 200?

如何解决Python:即使互联网关闭,响应代码也会返回 200?

一直在尝试创建一个循环,即使网络连接中断(try/except 块)也能保持迭代。在大多数情况下,它有效。但是在执行过程中,当我在关闭 Wi-Fi 后测试响应代码时,它仍然返回 200。 似乎无法理解为什么会这样。我的意思是,200 表示成功获取的请求,如果没有 Wi-Fi 连接就不可能发生,对吗?我读到响应代码 200 是认缓存的,是这个原因吗?我能做些什么来克服这个问题? 不能因为使用了后一种请求方法,对吗? 这是主要代码

base = datetime.datetime.today()
date_list = [base + datetime.timedelta(days=x) for x in range(numdays)]
date_str = [x.strftime("%d-%m-%Y") for x in date_list]

loop_starts = time.time()
for INP_DATE in date_str:
    try:
        # API to get planned vaccination sessions on a specific date in a given district.
        URL = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findBydistrict?district_id=" \
              f"512&date={INP_DATE}"
        response = requests.get(URL,headers=browser_header)
        response.raise_for_status()

    except requests.exceptions.HTTPError as errh:
        print("Http Error:",errh)
    except requests.exceptions.ConnectionError as errc:
        print("Error Connecting:",errc)
    except requests.exceptions.Timeout as errt:
        print("Timeout Error:",errt)
    except requests.exceptions.RequestException as err:
        print("OOps: Something Else",err)

    finally:
        print(f'Response code: {response.status_code}') #Why do you always return 200?!

        #code not important to the question
        if response.ok:
            resp_json = response.json()
            # read documentation to understand following if/else tree
            if resp_json["sessions"]:
                print("Available on: {}".format(INP_DATE))
                if print_flag == 'y' or print_flag == 'Y':
                    for center in resp_json["sessions"]:  # printing each center
                        if center["min_age_limit"] <= age:
                            print("\t","Name:",center["name"])
                            print("\t","Block Name:",center["block_name"])
                            print("\t","Pin Code:",center["pincode"])
                            #   print("\t","Center:",center)
                            print("\t","Min Age:",center['min_age_limit'])
                            print("\t Free/Paid: ",center["fee_type"])
                            if center['fee_type'] != "Free":
                                print("\t","Amount:",center["fee"])
                            else:
                                center["fee"] = '-'
                            print("\t Available Capacity: ",center["available_capacity"])
                            if center["vaccine"] != '':
                                print("\t Vaccine: ",center["vaccine"])
                            else:
                                center["vaccine"] = '-'
                            print("\n\n")

                            # Sending text message when availability of vaccine >= 10
                            # Creating text to send to telegram

                            txt = f'Available on: {INP_DATE}\nName: {center["name"]}\nBlock ' \
                                  f'Name: {center["block_name"]}\nPinCode: {center["pincode"]}\n' \
                                  f'Min Age: {center["min_age_limit"]}\nFree/Paid: {center["fee_type"]}\n' \
                                  f'Amount: {center["fee"]}\nAvailable Capacity: {center["available_capacity"]}\n' \
                                  f'Vaccine: {center["vaccine"]}\n\nhttps://selfregistration.cowin.gov.in/'
                            if center["available_capacity"] >= 10:
                                to_url = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=' \
                                         'HTML'.format(token,chat_id,txt)
                                resp = requests.get(to_url)
                                print('Sent')
            else:
                print("No available slots on {}".format(INP_DATE))
        else:
            print("Response not obtained.") #Should output when net is off.

        time.sleep(25)  # Using 7 requests in 1 second. 100 requests per 5 minutes allowed. You do the math.
        #  timing the loop
        Now = time.time()
        print("It has been {} seconds since the loop started\n".format(Now - loop_starts))

解决方法

像这样重写你的代码

  1. 响应不会在网络异常的情况下被覆盖,因此 response 是之前的值
  2. finally 是陷阱,因为即使捕获到异常,代码也会执行,这不是您想要的
  3. 在您的异常中使用 continue 重试
base = datetime.datetime.today()
date_list = [base + datetime.timedelta(days=x) for x in range(numdays)]
date_str = [x.strftime("%d-%m-%Y") for x in date_list]

loop_starts = time.time()
for INP_DATE in date_str:
    try:
        # API to get planned vaccination sessions on a specific date in a given district.
        URL = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id=" \
              f"512&date={INP_DATE}"
        response = requests.get(URL,headers=browser_header)
        response.raise_for_status()

    except requests.exceptions.HTTPError as errh:
        print("Http Error:",errh)
        continue
    except requests.exceptions.ConnectionError as errc:
        print("Error Connecting:",errc)
        continue
    except requests.exceptions.Timeout as errt:
        print("Timeout Error:",errt)
        continue
    except requests.exceptions.RequestException as err:
        print("OOps: Something Else",err)
        continue

    # will now only been displayed when you DO have a 200
    print(f'Response code: {response.status_code}') #Why do you always return 200?!

    #code not important to the question
    resp_json = response.json()
    # read documentation to understand following if/else tree
    if not resp_json["sessions"]:
        print("No available slots on {}".format(INP_DATE))
        continue

    print("Available on: {}".format(INP_DATE))
    if print_flag != 'y' and print_flag != 'Y':
        continue

    for center in resp_json["sessions"]:  # printing each center
        if center["min_age_limit"] > age:
            continue
        print("\t","Name:",center["name"])
        print("\t","Block Name:",center["block_name"])
        print("\t","Pin Code:",center["pincode"])
        #   print("\t","Center:",center)
        print("\t","Min Age:",center['min_age_limit'])
        print("\t Free/Paid: ",center["fee_type"])
        if center['fee_type'] != "Free":
            print("\t","Amount:",center["fee"])
        else:
            center["fee"] = '-'
        print("\t Available Capacity: ",center["available_capacity"])
        if center["vaccine"] != '':
            print("\t Vaccine: ",center["vaccine"])
        else:
            center["vaccine"] = '-'
        print("\n\n")

        # Sending text message when availability of vaccine >= 10
        # Creating text to send to telegram

        txt = f'Available on: {INP_DATE}\nName: {center["name"]}\nBlock ' \
              f'Name: {center["block_name"]}\nPinCode: {center["pincode"]}\n' \
              f'Min Age: {center["min_age_limit"]}\nFree/Paid: {center["fee_type"]}\n' \
              f'Amount: {center["fee"]}\nAvailable Capacity: {center["available_capacity"]}\n' \
              f'Vaccine: {center["vaccine"]}\n\nhttps://selfregistration.cowin.gov.in/'
        if center["available_capacity"] >= 10:
            to_url = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=' \
                     'HTML'.format(token,chat_id,txt)
            resp = requests.get(to_url)
            print('Sent')

    time.sleep(25)  # Using 7 requests in 1 second. 100 requests per 5 minutes allowed. You do the math.
    #  timing the loop
    now = time.time()
    print("It has been {} seconds since the loop started\n".format(now - loop_starts))

,

正如其他人评论和回复的那样,finally 在这里不合适。 allan.simon 提供了在异常处理程序中使用 continue 的解决方案。这当然是一个很好的解决方案。

另一种解决方案(不一定更好):将 finally 替换为 elseelse 语句中的 try 子句“如果控制流离开 try 套件,没有引发异常,并且没有执行 return、continue 或 break 语句,则执行。” (引用文档)。这正是您尝试使用此处的 finally 所做的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?