How do I serve an image from a python script?
gbreed at cix.compulink.co.uk
gbreed at cix.compulink.co.uk
Fri Jun 8 05:43:53 EDT 2001
In article <3B2039DB.8884C4B4 at yahoo.com>, haaserd at yahoo.com (haaserd)
wrote:
> Hi,
>
> I am trying to serve an image from a Python script using Apache under
> Windows. My simple HTML statement:
>
> <img src="ShowPict.py?fn=xxx" alt="a picture">
>
> ...and my simple script:
>
> #!c:/Python20/python.exe
> import sys
>
> def pix():
> n = 'c:/My Pictures/Sample.jpg'
> p = open(n,'rb')
> apix = p.read()
> p.close()
> sys.stdout.write("content-type: image/jpeg\n\n")
> sys.stdout.write(apix)
> sys.stdout.flush()
>
> if __name__ == '__main__':
> pix()
I've found this script to work on IIS:
import cgi
import sys, os
input = open(r'absolute.filename.gif','rb')
output = os.fdopen(sys.stdout.fileno(), 'wb')
output.write('Content-Type: image/gif\r\n\r\n')
output.write(input.read())
input.close()
# don't close stdout!
The only important difference with yours is that I'm using \r\n instead of
\n. I think that os.fdopen stuff is wank, but worth a try if all else
fails.
> As you can see I am ignoring the CGI fields for the moment and am just
> trying
> to serve up an image. Through debugging statements that I have
> removed, I
> know the program crashes on the statement
> sys.stdout.write(apix)
> if the picture is over 200,000 bytes.
That's above what I was testing with, hope it isn't too big a problem.
Perhaps writing out the file in chunks will fix it.
> On small images (10k), the script runs to completion, but no image
> appears.
> What am I doing wrong?
When you say no image appears, does that mean nothing's being sent from
the server? You can test this by changing the MIME type to text/plain
(and perhaps not using IE) so you'll see some garbage appear if it's
working.
Anyway, I expect what you're doing wrong is not setting binary output.
That would correlate with your not using the correct line termination
characters. So add a -u to the command line, however that's specified.
If it's that magic line at the top of the file, make it
#!c:/Python20/python.exe -u
Graham
More information about the Python-list
mailing list