Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python HTTP server that supports chunked encoding?

I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?

like image 865
slacy Avatar asked Apr 08 '09 22:04

slacy


3 Answers

Twisted supports chunked transfer encoding (API link) (see also the API doc for HTTPChannel). There are a number of production-grade projects using Twisted (for example, Apple uses it for the iCalendar server in Mac OS X Server), so it's quite well supported and very robust.

like image 78
Jarret Hardie Avatar answered Oct 18 '22 18:10

Jarret Hardie


Twisted supports chunked transfer and it does so transparently. i.e., if your request handler does not specify a response length, twisted will automatically switch to chunked transfer and it will generate one chunk per call to Request.write.

like image 2
mathieu Avatar answered Oct 18 '22 20:10

mathieu


You can implement a simple chunked server using Python's HTTPServer, by adding this to your serve function:

    def _serve(self, res):
        response = next(res)

        content_type = 'application/json'

        self.send_response(200)
        self.send_header('Content-Type', content_type)
        self.send_header('Transfer-Encoding', 'chunked')
        self.end_headers()

        try:
            while True:
                # This line removed as suggested by @SergeyNudnov
                # r = response.encode('utf-8')
                l = len(r)
                self.wfile.write('{:X}\r\n{}\r\n'.format(l, r).encode('utf-8'))

                response = next(it)
        except StopIteration:
            pass

        self.wfile.write('0\r\n\r\n'.encode('utf-8'))

I would not recommend it for production use.

like image 1
Orwellophile Avatar answered Oct 18 '22 19:10

Orwellophile