【发布时间】:2014-03-28 23:01:21
【问题描述】:
是否有更 Pythonic (2.7) 的方法来检查服务器是否有不包括使用 while True 的良好 status_code (200)?我的代码 sn-p 如下 - 它被多次调用:
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()
编辑:我在标题错误中包含了“if”循环。
【问题讨论】:
-
这个代码是用来检查服务器健康状况的工具吗?
-
@praveen 不,我需要 response.json() 中的数据。但服务器有限制,也可能发送非 200 码。
-
使用
while 1:如果while True:是问题,那是显而易见的解决方案。但真正的问题是什么?你能写更多吗? -
'while True' 不是问题,但我想问这些天在 python 中是否有更好的做法
-
还可以看看这个:stackoverflow.com/questions/14236426/… 有一个重试计数器可能会在您受到限制的情况下妨碍您
标签: python python-2.7 python-requests