2017-06-21 81 views

回答

0

render_GET通常在网络服务器上实现,但根据您的问题,似乎您正试图从Web服务器使用数据而不是服务它。

你想要的东西很容易使用Agent API实现。请从Twisted Web documentation中查看此示例。

from __future__ import print_function 

from pprint import pformat 

from twisted.internet import reactor 
from twisted.internet.defer import Deferred 
from twisted.internet.protocol import Protocol 
from twisted.web.client import Agent 
from twisted.web.http_headers import Headers 

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) 
d = agent.request(
    'GET', 
    'http://example.com/', 
    Headers({'User-Agent': ['Twisted Web Client Example']}), 
    None) 

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() 

当某物到达时,会调用dataReceived事件。

希望这会有所帮助。

+0

谢谢。但是在这个演示中,当一些原始数据到达时,'dataReceived'将被调用。就我而言,我希望在“块”到达时收到通知。这意味着,我不想处理http-chunk的解析器,只有解码后的“body” – Rex