[Twisted-web] Buffered requests

Donovan Preston dp at ulaluma.com
Thu Nov 4 14:02:14 MST 2004


On Nov 4, 2004, at 10:35 AM, Peter Hunt wrote:

> I'm wondering if there is a way that I can "buffer" a request, store
> the output it would normally send to the client in a string, and then
> output something different, such as a redirect, to the client.
>
> For example, it'd be nice if it worked like this:
>
> buffered_request.setHeader("Content-type","text/html")
> buffered_request.write("<html>Hello %s</html>" %
> buffered_request.args.get("name",["world"])[0])
> buffered_request.finish()
> output = buffered_request.getOutput()
> request.setHeader("Content-type","text/plain")
> request.write("The output that will be written to the client is:\n " + 
> output)
>
> The end result (in the browser) should be:
>
> The output that will be written to the client is:
> 200 OK
> Content-type: text/plain
>
> <html>Hello world</html>
>
> I've tried playing around with something called "queued", but I'm not
> sure if that's what I want. Essentially I just want to capture the
> output of a request in a string.

You'll have to do it yourself. You could just do it explicitly by 
constructing an object around the request and doing the buffering in 
that. Or you could try being really tricky and doing something like 
this (untested):

class Foo(Resource):
     def render_GET(self, request):
         buffer = StringIO()
         original_write = request.write
         request.write = buffer.write
         original_finish = request.finish
         request.finish = lambda: (original_write(buffer.getvalue()), 
original_finish())
         self.renderTheActualPage()
         return NOT_DONE_YET

nevow's rend.Page has a "buffered" attribute which, when set, does all 
this for you, so you can set headers any time during the rendering 
process and the headers will not be written until the entire body has 
been rendered.

dp




More information about the Twisted-web mailing list