簡體   English   中英

使用Twisted閱讀API響應

[英]Reading API response using Twisted

我已嘗試使用python Twisted網絡客戶端調用API后讀取響應。 我對傳遞給json結構的終結點進行了POST調用,然后它應該返回帶有消息(如果失敗)或json結構(如果成功)的狀態。

使用下面的代碼,我可以看到消息與狀態代碼一起被調用,但是我沒有看到message / 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()

您不需要所有這些絨毛代碼,如果您已經在使用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)

參考:請參閱此Stackoverflow鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM