Serving a file through HTTP

Gerhard Häring gh at ghaering.de
Tue Mar 18 09:21:52 EST 2003


gumuz at looze.net wrote:
> Ah, I'm sorry, I left something unclear in my message I think.
> 
> I mean, serving up binary files like music(mp3). It sounds very simple,
> but I have no clue how to stream such a file to the client. [...]

You're probably just thinking too complicated. From SimpleHTTPServer:

     def do_GET(self):
         """Serve a GET request."""
         f = self.send_head()
         if f:
             self.copyfile(f, self.wfile)
             f.close()

Let's adapt this slightly (untested):

     def do_GET(self):
         """Serve a GET request."""
         self.send_header("Content-Type", "audio/mp3")
         self.end_headers()

         my_mp3_file = open("Metallica - Nothing Else Matters.mp3", "rb")

         # Reading the entire file at once is probably not that great a
         # strategy.
         self.wfile.write(my_mp3_file.read())

         my_mp3_file.close()

This would probably quite a boring MP3 server, always serving the same 
file ;-)

-- Gerhard






More information about the Python-list mailing list