【问题标题】:Reading API response using Twisted使用 Twisted 读取 API 响应
【发布时间】:2023-03-30 17:20:02
【问题描述】:

在使用 python Twisted Web 客户端调用 API 后,我正在尝试读取响应。我已经对传入 json 结构的端点进行了 POST 调用,然后它应该返回带有消息(如果失败)或 json 结构(如果成功)的状态。

使用下面的代码,我可以看到消息与状态代码一起被调用,但我没有看到消息/json 结构。

“BeginningPrinter”永远不会被调用,我不明白为什么。

输出示例:

$ python sample.py 
Response version: (b'HTTP', 1, 0)
Response code: 401 | phrase : b'UNAUTHORIZED'
Response headers:
Response length: 28

很抱歉代码太长了,但我想确保它包含我用来运行它的所有内容。

from io import BytesIO
import json
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import FileBodyProducer

agent = Agent(reactor)

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10
        print('begin')

    def dataReceived(self, bytes):
        print('bytes')
        if self.remaining:
            display = bytes[:self.remaining]
            print('Some data received:')
            print(display)
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print('Finished receiving body:', reason.getErrorMessage())
        self.finished.callback(None)

TESTDATA = { "keySequence": "2019-07-14" }
jsonData = json.dumps(TESTDATA)
body = BytesIO(jsonData.encode('utf-8'))
body = FileBodyProducer(body)
headerDict = \
{
    'User-Agent': ['test'],
    'Content-Type': ['application/json'],
    'APIGUID' : ['ForTesting']
}
header = Headers(headerDict)

d = agent.request(b'POST', b' http://127.0.0.1:5000/receiveKeyCode', header, body)

def cbRequest(response):
    print(f'Response version: {response.version}')
    print(f'Response code: {response.code} | phrase : {response.phrase}')
    print('Response headers:')
    print('Response length:', response.length)
    print(pformat(list(response.headers.getAllRawHeaders())))
    print(response.deliverBody)
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished

d.addCallback(cbRequest)

def cbShutdown(ignored):
    #reactor.stop()
    pass

d.addBoth(cbShutdown)

reactor.run()

【问题讨论】:

  • 看起来你的 HTTP 响应说你没有被授权,这对我来说似乎很重要......你也验证了BeginningPrinter 实际上没有被调用,并且你验证了变量“完成”了吗?
  • @pjmaracs 在这种情况下,我提出 401 请求,因为 APIGUID 无效 - 有一个响应字符串: response = KeypadAPIThread.KeypadAPIEndpoint.response_class( response='Authorisation key is missing', status=401, mimetype='text') 返回响应
  • 好的,我明白了。在做了一些研究之后,我唯一能想到的是,也许你没有正确使用 Defered ......也许可以咨询this stack overflow question

标签: python twisted


【解决方案1】:

您不需要所有的绒毛代码,如果您已经在使用 Flask,那么您可以写入 API 并在几行中取回值,如果您不需要,那么 pip install 它是有意义的它让生活变得更轻松。

import json
import requests

headers = {
    'content-type': 'application/json',
    'APIGUID' : 'ForTesting'
}

conv = {"keySequence": "2019-07-14"}
s = json.dumps(conv) 
res = requests.post("http://127.0.0.1:5000/receiveKeyCode",data=s, headers=headers)
print(res.text)

参考:见this Stackoverflow link

【讨论】:

  • 谢谢你,它更短更简洁。我正在使用烧瓶。我不知道为什么大卫主义删除了原来的标签。
  • 这看起来不像是对我的问题的回答。问题似乎是关于如何编写一个基于 Twisted Web 的客户端来向 HTTP 服务器发出请求。服务器是否是烧瓶都没关系。而且基于请求的 HTTP 客户端不是基于 Twisted Web 的客户端。
  • @Jean-PaulCalderone 我实际上是在使用烧瓶来接收消息,所以露西托马斯的回应感觉足够有效,因为我可以只使用烧瓶而不再需要第二个库(Twisted)。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 2015-10-31
  • 2016-09-02
  • 2020-09-28
  • 2019-01-27
  • 2014-06-15
  • 2018-06-19
  • 1970-01-01
相关资源
最近更新 更多