這應該很簡單,因爲人們一直都這樣做。我想獲得POST請求的正文發送扭曲的Agent
。這是用扭曲的FileBodyProducer
創建的。在服務器端,我的render_POST
方法得到一個request
對象。
我該如何檢索身體?
服務器:
from twisted.web import server, resource
from twisted.internet import reactor
class Simple(resource.Resource):
isLeaf = True
def render_GET(self, request):
return "{0}".format(request.args.keys())
def render_POST(self, request):
return "{0}".format(request.data)
with open(request.args['filename'][0], 'rb') as fd:
fd.write(request.write())
site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()
客戶端:
from StringIO import StringIO
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.web.client import FileBodyProducer
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from pprint import pformat
class BeginningPrinter(Protocol):
def __init__(self, finished):
self.finished = finished
self.remaining = 1024 * 10
def dataReceived(self, 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)
agent = Agent(reactor)
body = FileBodyProducer(StringIO("hello, world"))
d = agent.request(
'POST',
'http://127.0.0.1:8080/',
Headers({'User-Agent': ['Twisted Web Client Example'],
'Content-Type': ['text/x-greeting']}),
body)
def cbRequest(response):
print 'Response version:', response.version
print 'Response code:', response.code
print 'Response phrase:', response.phrase
print 'Response headers:'
print pformat(list(response.headers.getAllRawHeaders()))
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
return finished
d.addCallback(cbRequest)
def cbShutdown(ignored):
reactor.stop()
d.addBoth(cbShutdown)
reactor.run()
唯一的文檔我能找到建立在消費者方面leave something to be desired。主要是,消費者如何使用write(data)
方法來獲得的結果?
我錯過了將這兩個組件連接在一起的位?
爲了將來的參考,我建議不要執行由os.stat()。st_size設置的內容長度的request.write(fd.read())。我遇到了一個問題,我在request.write(fd.read())處得到IOError設備上沒有剩餘空間。 如果你有內存,我建議首先將文件讀入緩衝區,然後根據len(buf)做內容長度。然後request.write(buf)。 – 2016-08-17 22:33:52