子类化static.File [英] Subclassing static.File

查看:127
本文介绍了子类化static.File的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Twisted的新手,我遇到了一些针对static.File扭曲的必要子类化的问题。我正在尝试在子类中设置请求标头。

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

第一位代码是子类定义本身(非常简单),而第二位是我代码中的初始化部分(这不是全部)我的代码)。我还有一个resource.Resource对象的子类,名为TestHandler。 WebFolder是另一个包含许多静态文件的文件夹。

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 /

除了root之外还有许多不同的路径。

With many different paths other than root.

推荐答案

代码中的问题是 render_GET 方法。它什么都不返回。基本上它必须返回同步响应的字符串和异步响应的 NOT_DONE_YET 值。在您的情况下 render_GET 返回(并且您的连接立即关闭)。

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

所以你必须在你的 render_GET 中进行较小的更改(添加适当的 return ):

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)

如果你检查twisted.web.static.py模块,你会发现File.render_GET生成了生产者并返回 NOT_DONE_YET 这使得连接保持不变直到它不存在明确关闭(在我们的例子中,在下载文件之后)。

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

这篇关于子类化static.File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆