Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted http gzip support

I'm looking to help an open source project with Python.
As far as I could tell, Twisted doesn't didn't support sending and receiving gzip information with HTTP (as of 2011). http://twistedmatrix.com/trac/ticket/104

Google seems to confirm it, since I couldn't find any mention of it the documentation. My question is whether I'm right about this, or if this has changed? Alternatively, is it actually useful to anyone? I guess there's a reason it hasn't been implemented yet.

Sorry if this isn't the right place to ask...

like image 520
Tiersen Avatar asked Mar 25 '11 04:03

Tiersen


2 Answers

From the documentation for EncodingResourceWrapper:

Note that the returned children resources won't be wrapped, so you have to explicitly wrap them if you want the encoding to be applied.

So if a Resource implements getChild, then you need to wrap that resource as well.
For example:

from twisted.web.server import Site, GzipEncoderFactory
from twisted.web.resource import EncodingResourceWrapper
from twisted.web import static
from twisted.internet import reactor
from twisted.python import log
import sys
log.startLogging(sys.stdout)

class WebServer(static.File):        
    def getChild(self, path, request):
        child = static.File.getChild(self, path, request)            
        return EncodingResourceWrapper(child, [GzipEncoderFactory()])

resource = WebServer('/tmp')

site = Site(resource)
reactor.listenTCP(8080, site)
reactor.run()

you can test it with netcat:

printf 'GET /  HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip,deflate\r\nConnection: close\r\n\r\n' | nc localhost 8080
like image 130
Dan Brough Avatar answered Nov 06 '22 14:11

Dan Brough


This is now possible using Resource Encoders. Quoting from that link:

from twisted.web.server import Site, GzipEncoderFactory
from twisted.web.resource import Resource, EncodingResourceWrapper
from twisted.internet import reactor

class Simple(Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html>Hello, world!</html>"

resource = Simple()
wrapped = EncodingResourceWrapper(resource, [GzipEncoderFactory()])
site = Site(wrapped)
reactor.listenTCP(8080, site)
reactor.run()

See the link for more information. The ticket in the question is now closed as well.

like image 6
Daniel C. Sobral Avatar answered Nov 06 '22 14:11

Daniel C. Sobral