Subclassing static.File

邮差的信 提交于 2019-12-10 14:49:25

问题


I'm new to Twisted and I'm having trouble with some necessary subclassing for the static.File in twisted. i'm trying to set request headers within the subclass.

class ResponseFile(static.File):

    def render_GET(self, request):
        request.setHeader('Content-Disposition', ['attachment ; filename="tick_db_export.csv"'])
        static.File.render_GET(self, request)

if __name__ == "__main__":
    from twisted.internet import reactor
    root = ResponseFile('WebFolder')
    testHandler = TestHandler()
    root.putChild('main', testHandler)
    reactor.listenTCP(3650, server.Site(root))
    reactor.run()

The first bit of code is the subclass definition itself (pretty straightforward), while the second bit is the initialization portion from my code (this isn't all of my code). I've have also subclassed a resource.Resource object called TestHandler. WebFolder is another folder containing many static files.

However, I am getting most of these types of exception when making calls to the server.

Unhandled Error
Traceback (most recent call last):
Failure: exceptions.RuntimeError: Producer was not unregistered for /

With many different paths other than root.


回答1:


The problem in your code is in render_GET method. It returns nothing. Basically it must return string for synchronous response and NOT_DONE_YET value for asynchronous response. In your case render_GET returns None (and your connection get closed immediately).

So you have to make a smaller change in your render_GET (add proper return):

def render_GET(self, request):
    request.setHeader('Content-Disposition', ['attachment ; filename="tick_db_export.csv"'])
    return static.File.render_GET(self, request)

If you inspect twisted.web.static.py module you'll find that File.render_GET makes producer and returns NOT_DONE_YET which makes connection to hold on until it is not explicitly closed (in our case, after file is downloaded).



来源:https://stackoverflow.com/questions/11958272/subclassing-static-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!