是否有更 Pythonic (2.7) 的方法来检查服务器是否有良好的 status_code (200),而不包括使用 while True
?我的代码片段如下 - 它被调用了很多次:
import time
import json
from datetime import datetime
import requests
while True:
response = requests.get('http://example.com')
if response.status_code != 200:
print 'sleeping:',str(datetime.now()),response.status_code
print 'sleeping:',str(datetime.now()),response.headers
time.sleep(5.0)
else: break
if "x-mashery-error-code" in response.headers:
return None
return response.json()
编辑:我在 header 错误中加入了“if”循环。
最佳答案
您可以使用 Event Hooks
requests.get('http://example.com', hooks=dict(response=check_status))
def check_status(response):
if response.status_code != 200:
print 'not yet'
关于python - 在 Python 2.7 中执行 http 请求时使用 'while True',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035936/