Python 使用Twisted读取API响应
在使用python Twisted web客户端调用API之后,我正在尝试读取响应。我对传入json结构的端点进行了POST调用,然后它将返回一个状态,其中包含一条消息(如果失败),或者一个json结构(如果成功) 使用下面的代码,我可以看到消息与状态代码一起被调用,但是我没有看到消息/json结构 “开始印刷”从来没有接到过电话,我不明白为什么 输出示例:Python 使用Twisted读取API响应,python,twisted,Python,Twisted,在使用python Twisted web客户端调用API之后,我正在尝试读取响应。我对传入json结构的端点进行了POST调用,然后它将返回一个状态,其中包含一条消息(如果失败),或者一个json结构(如果成功) 使用下面的代码,我可以看到消息与状态代码一起被调用,但是我没有看到消息/json结构 “开始印刷”从来没有接到过电话,我不明白为什么 输出示例: $ python sample.py Response version: (b'HTTP', 1, 0) Response code:
$ 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()
您不需要所有这些无用的代码,如果您已经在使用Flask,那么您可以写入API并在几行内获取值,如果您不需要,那么pip安装它是有意义的,因为它使生活变得更加轻松
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)
参考资料:请参见您的HTTP响应似乎表明您未经授权,这对我来说意义重大……您是否已验证BeginningPrinter实际上未被调用,您验证了变量'finished'的值了吗?@pjmaracs在本例中,我提出401请求,因为APIGUID无效-有一个响应字符串:response=keypadipithread.keypadipendpoint.response_class(response='authorization key is missing',status=401,mimetype='text')回答好了,我现在明白了。在做了一点研究之后,我唯一能想到的是,也许你没有正确地使用延迟。。。也许可以咨询一下,谢谢你,它短得多,干净得多。我用的是烧瓶。我不知道为什么Davidism删除了原来的标签。在我看来,这并不是问题的答案。问题似乎是关于如何编写基于Web的Twisted客户端向HTTP服务器发出请求。服务器是否可用并不重要。而且基于请求的HTTP客户端不是基于Web的Twisted客户端。@Jean-PaulCalderone我实际上使用flask来接收消息,因此Lucy Thomas的响应足够有效,因为我可以只使用flask,不再需要第二个库(Twisted)。