【发布时间】:2021-08-09 16:36:09
【问题描述】:
一直在尝试创建一个循环,即使网络连接中断(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))
【问题讨论】:
-
肯定是因为
finally无论如何都会执行,所以承认你在请求过程中抛出了异常,函数`requests.get(URL, headers=browser_header)`还没有返回,所以response =还没有被执行,所以你仍然有循环的前一次迭代的值,你当然想要在每个异常中continue并且没有finally -
@allan.simon,实际上它会保留之前的
status_code,即使在退出之后。解决方案 (种类) 是在每个请求之前将status_code设为空response.status_code = 0 -
@OlvinRoght 在程序停止并重新启动后,“退出后”是什么意思?问题中似乎没有说明,这意味着wifi在执行期间被切断了?
-
@OlvinRoght 编辑状态码感觉怪怪的,不应该在这里
finally,因为您不想在已经显示的错误消息之外显示任何内容? -
@allan.simon,我的意思是如果你发送请求并且一次迭代会引发异常,
response对象根本不会被更新。可以设置response = None
标签: python python-requests response httpresponse http-response-codes