【发布时间】:2021-11-13 18:00:59
【问题描述】:
我有以下发出 HTTP GET 请求的方法。我为其添加了一些错误处理,以确保它不会返回响应,除非没有网络错误。
当方法如下Pycharm不认为response变量可能在赋值前被引用:
def requests_with_error_handling(self, url):
while True:
try:
response = requests.get(url, headers=headers, proxies=random_proxy())
break
except Exception as e:
self.pretty_print(e)
time.sleep(1)
return response
但是,当我在 except 块的底部添加 continue 语句时,PyCharm 不喜欢它并说在赋值之前可能会引用 response 变量,即使我相信两个代码块都可以完全相同的事情,continue 语句是不必要的,因为如果continue 不存在,执行将移至while 循环的顶部。
def requests_with_error_handling(self, url):
while True:
try:
response = requests.get(url, headers=headers, proxies=random_proxy())
break
except Exception as e:
self.pretty_print(e)
time.sleep(1)
continue
return response
这是 Pycharm 的错误还是我对 Python 中程序控制流的理解不正确?
【问题讨论】:
-
你在那里使用
continue的目的是什么? -
OP 想要一遍又一遍地重试相同的请求,直到返回一个有效的响应......因为对 requests.get 的调用没有改变,所以很有可能它永远只是在死循环
-
当然,但即使没有
continue,它也会重试该请求。
标签: python python-3.x pycharm