python - 在 Python 2.7 中执行 http 请求时使用 'while True'

标签 python python-2.7 python-requests

是否有更 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/

相关文章:

python - 使用 requests-oauthlib 设置 HTTP User-Agent header

python - 为什么ndarray显示为黑色图像?

python - 如何在 Python 中解析和加载本体?

python - 虚拟环境中的 Opencv3 和 Python 2.7 - AttributeError : 'module' object has no attribute 'createLBPHFaceRecognizer'

python - 如何使用循环制作字典?

python - 在请求中发送多部分表单数据时是否需要使用 with 语句?

python - 使用 python 请求下载 *.gz 压缩文件会损坏它

python - POST请求表Python3

python - 是否可以通过 QML 从 PySide2 插槽(服务调用)获取对象列表?

python - 在django模板中将unicode解码为字符串