Search code examples
pythonfile-iobasehttpserver

Python BaseHTTPServer serving files faster


I have some relatively large .js files (flot and jquery) to serve with a Python BaseHTTPServer.

Currently I am using:

with open(curdir + sep + self.path, 'rb') as fd:
    self.wfile.write(fd.read())

But its rather slow, even loading the files from the same machine (> a second to fetch these). I imagine this is reading the entire file into RAM and then writing from that, is there a way I can speed this up a little?


Solution

  • Indeed, your code buffers everything before sending it off to the client. To stream the response instead, look at how SimpleHTTPServer does it.

    It uses shutil.copyfileobj, which does exactly that. Use:

    import shutil
    shutil.copyfileobj(fd, self.wfile)