CGI python 3 write RAW BINARY

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed May 5 01:09:01 EDT 2010


En Sat, 01 May 2010 07:52:01 -0300, Dodo <dodo_do_not_wake_up at yahoo.fr>  
escribió:

> Le 30/04/2010 17:52, Antoine Pitrou a écrit :
>> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a écrit :
>>> ....I don't get a thing.
>>> Now with the fix :
>>> All browsers shows a different thing, but not the image!
>>> http://ddclermont.homeip.net/misc/python/
>>>
>>> If I save it to computer :
>>> * Windows image viewer won't read it
>>> * Irfanview can read it without problems
>>
>> Did you set the content-type and content-length in the HTTP headers?
>> Can you post your code?
>>
>>
> I didn't know about content-lenght
> Here's the new code (I used a fixed image patch to make sure this is not  
> the source of the problem)
>
>
> #!/usr/bin/python3
> import cgi, sys, cgitb
> cgitb.enable()
>
> f = open("/home/dodo/54.jpg", "rb")
> data = f.read()
> l = len(data)
> f.close()
>
> print("Content-type:image/jpg\nContent-length:%d\n\n" % l)
>
> sys.stdout.flush()
> sys.stdout.buffer.write( data )

Computers are dumb. You have to speak to them very slow and clearly in  
order to be understood :)

You need a space after those ':'. The correct media type for JPEG images  
is image/jpeg. And (the important thing) you have one more \n than  
necessary. Each header field finishes with \n; an empty line (just \n)  
marks the end of all headers; the body [your image] must follow  
immediately.

#!/usr/bin/python3
import cgi, sys, cgitb
cgitb.enable()

f = open("/home/dodo/54.jpg", "rb")
data = f.read()
l = len(data)
f.close()

print("Content-Type: image/jpeg\nContent-Length: %d\n" % l)

sys.stdout.flush()
sys.stdout.buffer.write( data )

(Probably, a better way would be to replace all those \n with \r\n, and  
not use print at all, but the above code is good enough).

-- 
Gabriel Genellina




More information about the Python-list mailing list