Search code examples
pythontwisted

twisted.web.resource.Resource with twisted.web.template.Element example


I want to use twisted.web templates together twisted.web resources.

But I just don't get, how to make them work together.

I tried using, flatten(request, MyElement(), request.write), but it ends up throwing an exception: Request.write called on a request after Request.finish was called.

Could someone provide me a very basic example how to use the two classes together?


Solution

  • It sounds like you forgot to return NOT_DONE_YET from your render() method, and therefore finish() was called for you immediately. Something like the following should be somewhere in Twisted itself, to help with exactly this problem:

    from twisted.web.resource import Resource
    from twisted.web.template import flatten
    from twisted.web.server import NOT_DONE_YET
    
    class ElementResource(Resource):
        def __init__(self, element):
            Resource.__init__(self)
            self.element = element
        def render_GET(self, request):
            d = flatten(request, self.element, request.write)
            def done(ignored):
                request.finish()
                return ignored
            d.addBoth(done)
            return NOT_DONE_YET