python-3.x - 如何正确使用请求异常
问题描述
我目前正在研究如何正确使用请求异常。我目前已经做了这样的事情:
主文件
import requests
import exceptions_own
from requests.exceptions import ConnectionError, ProxyError, ReadTimeout, RequestException, Timeout
simpleException = exceptions_own({})
# Exception
class TooManyFailedRequests():
pass
class TooManyTimedOut():
pass
------------------------------------------------------------------------
def run_request() -> Iterable[Response]:
try:
return get("https://stackoverflow.com/12354") # Should return 400
except TooManyFailedRequests as err:
raise TooManyFailedRequests("msg")
def get_request(site_url) -> Iterable[Response]:
while True:
try:
response = requests.get(site_url, timeout=10)
if response.ok:
return response
else:
if response.status_code in {429, 403, 404}:
try:
response.raise_for_status()
except Exception as err:
simpleException.check(
exception=err
)
continue
except (ReadTimeout, Timeout, ConnectionError, ProxyError) as err:
if "503 Service Unavailable" not in str(err):
simpleException.check(
exception=TooManyTimedOut,
)
else:
continue
except RequestException:
continue
except Exception as unexpected:
simpleException.check(
exception=unexpected
)
if __name__ == "__main__":
run_scraper()
exceptions_own
class ExceptionCounter:
"""
Counter to check if we get exceptions x times in a row.
"""
def __init__(self, limits):
self.limits = limits
self.exception_counts: DefaultDict[Type[Exception], int] = defaultdict(int)
def check(self, exception):
allowed_count = self.limits.get(type(exception), 3)
self.exception_counts[type(exception)] += 1
if self.exception_counts[type(exception)] >= allowed_count:
raise
def reset(self):
self.exception_counts.clear()
我目前遇到的问题是:
if response.status_code in {429, 403, 404}:
我确实认为以这种方式引发异常是不正确的方法,但我希望我的 simpleException 计数器仅计算状态码 429、403、404 的异常run_scraper()
例如,如果我们被提出,我该如何提出异常if "503 Service Unavailable" not in str(err):
?
解决方案
推荐阅读
- amazon-web-services - Elastic Beanstalk 504 网关错误
- python - 如何在 keras 中获得输出 K.sqrt()?
- php - 多次左加入同一张表
- django - 用户匹配查询不存在:Django
- java - KStream-GlobalKTable join 可以为特定搜索返回多个匹配记录吗?
- xamarin.forms - Xamarin.UWP 段落完整理由部分工作
- html - 相同的 Chrome 版本,不同的计算机显示不同的网页
- microsoft-teams - 是否有可能获得与给他电子邮件的人聊天的链接?
- mysql - 优化 MYSQL 中的 UPDATE JOIN 查询
- c++ - 为什么我可以用 int 初始化字符串?