【发布时间】:2021-02-27 10:26:49
【问题描述】:
我一直在尝试学习如何正确编写计数器和“停止器”,例如状态 403 x 连续 10 次,或者我连续 10 次遇到连接错误。
现在我做了这样的事情:
import requests
import time
from requests.exceptions import ConnectionError, ReadTimeout, RequestException, Timeout
exception_counter = 0
while True:
try:
response = requests.get("https://stackoverflow.com/", timeout=12)
if response.ok:
print("Very nice")
time.sleep(60)
else:
print(
f'[Response -> {response.status_code}]'
f'[Response Url -> {response.url}]'
)
time.sleep(60)
if response.status_code == 403:
if exception_counter >= 10:
print("Hit limitation of counter: Response [403]")
time.sleep(4294968)
exception_counter += 1
except (ConnectionError) as err:
print(err)
time.sleep(random.randint(1, 3))
if exception_counter >= 10:
print(f"Hit limitation of coonnectionerror {err}")
time.sleep(4294968)
continue
exception_counter += 1
continue
except (ReadTimeout, Timeout) as err:
print(err)
time.sleep(random.randint(1, 3))
continue
except RequestException as err:
print(err)
time.sleep(random.randint(1, 3))
continue
except Exception as err:
print(err)
time.sleep(random.randint(1, 3))
if exception_counter >= 10:
print(f"Hit limitation of Exception {err}")
time.sleep(4294968)
continue
exception_counter += 1
continue
但是,我并不担心我在不同地方重复相同代码的地方是否正确。与我在不同地方重复相同代码的做法相比,我想知道如何以正确和正确的方式实际做到这一点
编辑:
更新代码:
现在的问题是,每当我们成功打印时,我想重置计数器,但现在没有。
import time
import requests
class ExceptionCounter:
def __init__(self):
self.count = 0
def check(self, message):
self.count += 1
print(self.count)
if self.count > 3:
print(message, 'exceeded 3 counts')
time.sleep(6000)
exception_counter = ExceptionCounter()
def main():
while True:
response = requests.post("https://www.google.se/")
print(response.status_code)
if response.ok:
print("Yay! Now I want to reset my counter because it got successful!")
else:
exception_counter.check(f"Ahhhh, wrong status code! {response.status_code}!")
time.sleep(1)
main()
【问题讨论】:
-
鉴于编辑,只需在
if response.ok:下添加exception_counter.count = 0。我仍然建议为此使用内置机制,而不是滚动您自己的解决方案。
标签: python python-3.x exception count