有没有一种方法可以使用python轮询函数提取http响应
我使用以下代码轮询发布/订阅服务器有没有一种方法可以使用python轮询函数提取http响应,python,http,publish-subscribe,polling,Python,Http,Publish Subscribe,Polling,我使用以下代码轮询发布/订阅服务器 import requests polling2.poll(lambda: requests.get('http://google.com').status_code == 200, step=60, poll_forever=True) 如果返回true,是否有方法访问响应体以获取特定字段?在我的例子中,它返回一个json响应您可以将poll()结果分配给变量,它将由lambda返回值 result = polling2.p
import requests
polling2.poll(lambda: requests.get('http://google.com').status_code == 200,
step=60,
poll_forever=True)
如果返回true,是否有方法访问响应体以获取特定字段?在我的例子中,它返回一个json响应您可以将poll()
结果分配给变量,它将由lambda
返回值
result = polling2.poll(lambda: requests.get('http://google.com').status_code == 200,
step=60,
poll_forever=True)
但在当前代码中,lambda
返回True
,result
将为True
,并且将无法访问请求
但是您可以使用check\u 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
返回response
,poll
将此response
发送到函数测试
,函数检查状态\u code
。如果test
将返回True
,则它将响应
至结果
,您可以使用.text
、.content
或.json()
我在的源代码中找到了它
编辑:它显示如何使用
collect\u value=
。但是queue
获取所有值,除了result
中的最后一个值。因此,它收集状态与200
不同的响应的结果(如果出现错误,则收集错误消息)
您可以使用request.get从python请求本身获取内容(',我不熟悉python轮询,所以这是一个建议什么是
poolg2.poll
?你是如何创建的?你使用了什么模块?谢谢,这就是我要找的。你知道吗,如何在这个方法中使用collect_value queue?你必须创建自己的queue.queue()
并将其与collec\u value=
一起使用。运行后,您可以使用.empty()
和.get()
从队列中获取值。但队列将包含所有值,除了在结果中获取的最后一个值。我使用队列添加了示例代码。但它是空的,因为第一个请求。get()
有状态200
。它需要几次给出不同状态的函数。感谢代码示例。我的程序中有一个特定的需求。我的发布/订阅url包含一个包含多条消息的队列。我始终希望使用轮询函数获取最新消息。我可以使用collect\u值来实现此功能,还是有不同的如何做到这一点?请帮助获取最新消息您必须从队列获取所有消息,最后一条消息将是最新的-,而不是我的队列。empty():last=my_queue.get()
>我不知道为什么要为此使用轮询
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)