CGI python 3 write RAW BINARY

Dodo dodo_do_not_wake_up at yahoo.Fr
Thu Apr 29 06:53:53 EDT 2010


Le 29/04/2010 01:45, Antoine Pitrou a écrit :
> Le Wed, 28 Apr 2010 23:54:07 +0200, Dodo a écrit :
>
>> Help! this is driving me crazy lol
>> I want to print raw binary data to display an image file BUT
>> python3 outputs b'<binary data>' instead of<binary data>.... so the
>> browser can't read the image!!
>>
>>    f = open("/some/path/%s" % x, 'rb')
>>    print(f.read())
>
> print() implicitly converts its arguments to str (i.e. unicode strings)
> and then writes them to sys.stdout, which is a text IO wrapper.
> If you want to bypass the unicode layer, you have to use
> sys.stdout.buffer instead.
> That is:
>
> sys.stdout.buffer.write(f.read())
>
> Regards
>
> Antoine.
>

@Gary : How do I reply to a http request then?

@Antoine : It not sys.stdout.buffer.write but sys.stdout.write() 
instead. But it still doesn't work, now I have empty content

#!/usr/bin/python3
import cgi, os, sys
form = cgi.FieldStorage()
all = os.listdir("/some/path/with/files/")
for x in all:
	if x.find( form['id'].value ) != -1:
		ext = x.split(".")[-1]
		print("Content-type:image/%s\n\n" % ext)
		f = open("/some/path/with/files/%s" % x, 'rb')
		sys.stdout.write( f.read() )
		f.close()
		break

Dorian



More information about the Python-list mailing list