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

Spe*_*ins 1 python asynchronous http twisted treq

我试图从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, [])
Run Code Online (Sandbox Code Playgroud)

这是回溯:

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

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

not*_*.no 5

现在我来看一下,这个例子非常糟糕,特别是如果您是新手。请尝试一下:

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)
Run Code Online (Sandbox Code Playgroud)

你真的必须知道的唯一的事情就是.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
Run Code Online (Sandbox Code Playgroud)

这一treq.content()系列功能使您可以轻松地仅返回您所关心的内容并对其进行处理。