【问题标题】:Is there a "Chunk Received" callBack in twisted web扭曲的网络中是否有“收到的块”回调
【发布时间】:2017-06-21 05:43:54
【问题描述】:

我已经尝试了 render_GET,它只会在接收和缓冲整个块体时调用。

如何获取部分中继数据?我需要处理连续的数据(如流),它是一个长期存在的连接(> 10分钟)。

谁能帮帮我!

【问题讨论】:

    标签: python twisted chunked-encoding twisted.web


    【解决方案1】:

    render_GET 通常在网络服务器上实现,但根据您的问题,您似乎是在尝试使用来自网络服务器的数据而不是提供服务。

    使用代理 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 事件。

    希望这会有所帮助。

    【讨论】:

    • 谢谢。但是在这个演示中dataReceived 会在一些原始数据到达时被调用。就我而言,我想在“块”到达时得到通知。这意味着,我不想处理 http-chunk 的解析器,只处理解码的“body”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多