how to serve image files without disk use?

Carsten Haese carsten at uniqsys.com
Fri Dec 29 11:07:41 EST 2006


On Fri, 2006-12-29 at 09:30 -0600, Chris Mellon wrote:
> On 12/28/06, Ray Schumacher <rays at blue-cove.com> wrote:
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > s.bind((HOST, PORT))
> > s.listen(1)
> > conn, addr = s.accept()
> > while 1:
> >      data = conn.recv(1024)
> >      if data[:3] == 'GET':
> >          conn.send("HTTP/1.0 200 OK"+"\015\012")
> >          conn.send("Server: RJS_video/0.0.1"+"\015\012")
> >          conn.send("Content-type: image/bmp"+"\015\012")
> >          conn.send("Content-Length: "+str(352*288*3+256)+"\015\012")
> >          conn.send("\015\012")
> >          fh = file('temp.jpg', 'rb')
> >          conn.send(fh.read())
> >          fh.close()
> >      else: break
> >
> > But, how can I avoid disk writes? wx's *.SaveFile() needs a string
> > file name (no objects).
> > I'm going to investigate PIL's im.save(), as it appears to allow
> > file-objects.
> >
> 
> wx.Image.GetData() returns the raw image data as a Python string.

In addition to what Chris said, is there a reason why you're reinventing
the wheel instead of using available components? BaseHTTPServer can take
care of the nitty-gritty details of the socket communication for you.
Here's an example that can easily be extended to suit your simple image
serving need:

###############################################################
import BaseHTTPServer

class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_GET(self):
    self.wfile.write("HTTP/1.0 200 OK\r\n")
    self.wfile.write("Content-Type: text/plain\r\n")
    self.wfile.write("\r\n")
    self.wfile.write("This is a test.")

s = BaseHTTPServer.HTTPServer(("",8080), MyRequestHandler)
s.serve_forever()
###############################################################

Hope this helps,

Carsten.





More information about the Python-list mailing list