gpt4 book ai didi

python - 如何从 treq 请求中获取响应文本?

转载 作者:可可西里 更新时间:2023-11-01 16:51:22 25 4
gpt4 key购买 nike

我试图开始使用 treq 库的一些示例代码,但收效甚微。虽然获取请求响应的状态代码和一些其他属性很容易,但获取响应的实际文本有点困难。此示例代码中可用的 print_response 函数在我的版本中不存在:

from twisted.internet.task import react
from _utils import print_response

import treq


def main(reactor, *args):
d = treq.get('http://httpbin.org/get')
d.addCallback(print_response)
return d

react(main, [])

这是回溯:

Traceback (most recent call last):
File "test.py", line 2, in <module>
from _utils import print_response
ModuleNotFoundError: No module named '_utils'

我真的不确定从这里到哪里去...任何帮助将不胜感激。

最佳答案

现在我看了一下,这个例子非常糟糕,特别是如果你是 twisted 的新手。请试一试:

import treq
from twisted.internet import defer, task

def main(reactor):
d = treq.get('https://httpbin.org/get')
d.addCallback(print_results)
return d

@defer.inlineCallbacks
def print_results(response):
content = yield response.content()
text = yield response.text()
json = yield response.json()

print(content) # raw content in bytes
print(text) # encoded text
print(json) # JSON

task.react(main)

您真正需要知道的唯一一件事是 .content().text().json() 返回Deferred 最终返回响应主体的对象。为此,您需要yield 或执行回调。

假设您只想要文本内容,您可以这样做:

def main(reactor):
d = treq.get('https://httpbin.org/get')
d.addCallback(treq.text_content)
d.addCallback(print) # replace print with your own callback function
return d

treq.content() 函数行可以很容易地只返回内容,如果这就是您所关心的,并用它做一些事情。

关于python - 如何从 treq 请求中获取响应文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com