【问题标题】:Is there a way to extract the http response using python polling function有没有办法使用 python 轮询函数来提取 http 响应
【发布时间】:2019-10-29 00:11:35
【问题描述】:

我正在使用以下代码来轮询发布/订阅服务器

    import requests
    polling2.poll(lambda: requests.get('http://google.com').status_code == 200,
    step=60,
    poll_forever=True)

如果返回 true,有没有办法访问响应正文以获取特定字段?在我的情况下,它返回一个 json 响应

【问题讨论】:

  • 您可以使用 request.get('google.com').content 从 python 请求本身获取内容,我不熟悉 python 轮询,所以这是一个建议 request response
  • pooling2.poll 是什么?你是如何创造它的?你用的是什么模块?

标签: python http publish-subscribe polling


【解决方案1】:

您可以将poll() 结果赋值给变量,它的值将由lambda 返回

result = polling2.poll(lambda: requests.get('http://google.com').status_code == 200, 
                       step=60, 
                       poll_forever=True)

但在当前代码中 lambda 返回 Trueresult 将是 True 并且将无法访问 requests

但是您可以使用check_success= 以不同的方式编写它来测试状态

import requests
import polling

def test(response):
    return response.status_code == 200

result = polling.poll(lambda: requests.get('http://google.com'), 
                      step=60, 
                      poll_forever=True, 
                      check_success=test)

print(result.text)

现在lambda 返回responsepoll 将此response 发送到函数test 以检查status_code。如果test 将返回True,那么它会将response 分配给result,您可以使用.text.content.json()


我在polling.py的源代码中找到了它


编辑:它展示了如何使用collect_value=。但是queue 获取除result 中的最后一个值之外的所有值。因此,它会收集状态与 200 不同的响应的结果(或错误消息,如果它们出现错误)。

import requests
import polling
import queue

def test(response):
    return response.status_code == 200

my_queue = queue.Queue()

result = polling.poll(lambda: requests.get('http://google.com'), 
                      step=60, 
                      poll_forever=True, 
                      check_success=test,
                      collect_value=my_queue)

if my_queue.empty():
    print('empty')
else:
    while not my_queue.empty():
        print(my_queue.get())

#print(result.text)

【讨论】:

  • 谢谢,这正是我想要的。你知道如何在这个方法中使用 collect_value 队列吗?
  • 您必须创建自己的queue.Queue() 并将其与collec_value= 一起使用。运行后,您可以使用.empty().get() 从队列中获取值。但是队列将具有除您在results 中获得的最后一个值之外的所有值。
  • 我用Queue 添加了示例代码。但它是空的,因为第一个requests.get() 的状态为200。它需要几次给出不同状态的函数。
  • 感谢代码示例。我的程序有一个特定的需求。我的 pub/sub url 包含一个包含多条消息的队列。我总是想使用轮询功能获取最新消息。我可以使用 collect_value 来实现这一点,还是有其他方法可以做到这一点?请帮忙
  • 要获取最新消息,您必须从队列中获取所有消息,最后一条消息将是最新消息 - while not my_queue.empty(): last = my_queue.get()> 我不知道为什么要为此使用 polling
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多