[英]Python: Response code returns 200 even when internet is turned off?
一直在嘗試創建一個循環,即使網絡連接中斷(嘗試/除外塊),它也會繼續迭代。 在大多數情況下,它有效。 但是在執行過程中,當我在關閉 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))
像這樣重寫你的代碼
response
是之前的值finally
是陷阱,因為即使捕獲到異常也會執行代碼,這不是您想要的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
的解決方案。 這當然是一個很好的解決方案。
另一種解決方案(不一定更好):用else
替換finally
。 try
語句中的else
子句“如果控制流離開 try 套件,沒有引發異常,並且沒有執行 return、continue 或 break 語句,則執行。” (引用文檔)。 這正是您在finally
中嘗試做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.