Tom Sheffler | 19 Apr 2012 17:37
Picon
Gravatar

Best way to avoid chunked encoding in HTTP Resource response?

A straightforward use of a series of request.write()s with a request.finish() in the render_GET() method of a resource defaults to chunked encoding.  I can avoid the chunked encoding by computing the entire response first using a StringIO (as shown below) and explicitly putting the "Content-Length" header in myself.


Is this the best (or recommended) way to create such a response?

Thx - Tom

=============

class myresource(Resource):

  def render_GET(self, response):
    output = StringIO.StringIO()
    output.write("...")
    output.write("...")
    ...

    data = output.getvalue()
    output.close()

    # Write the response data.  "content-length" suppresses chunked coding
    request.setHeader('content-length', len(data))
    request.write(data)
    request.finish()
    return True

_______________________________________________
Twisted-web mailing list
Twisted-web <at> twistedmatrix.com
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web
Ivan Kozik | 19 Apr 2012 19:20
Favicon
Gravatar

Re: Best way to avoid chunked encoding in HTTP Resource response?

On Thu, Apr 19, 2012 at 15:37, Tom Sheffler <tom.sheffler <at> gmail.com> wrote:
> Is this the best (or recommended) way to create such a response?

I don't think there's any need to close your StringIO.  You can also
use cStringIO.StringIO for better performance.  And you can just
return a string from your render_GET.  So, like this (untested):

 def render_GET(self, response):
    output = cStringIO.StringIO()
    output.write("...")
    output.write("...")
    return output.getvalue()

Ivan

Gmane