WebPython - Sending an Image/binary-data out (Testing)

My biggest worry was sending out binary data to the browser. On looking at FastCGI code it looked like it was using ASCII character buffers which was further disappointing. And, to make matters worse, my first piece of python code wasn't working. Here's the code:

import sys
sys.stdout.write("Content-Type: image/png\r\n\r\n");
f = open("/tmp/WebPython-128px.png", "rb");
d = f.read();

sys.stdout.write(d); #Gave an exception
#or
#os.write(sys.stdout.fileno(), d ); 
#Didn't give any errors but didn't work either.
#This code doesn't work with WebPython 






Used GDB on WebPython by attaching to the WebPython process and it appeared that os.write() was infact working but there was something strange about it. The sys.stdout.write() was sending the data after os.write(). Perhaps a Python3 bug ? or, the functions os.write() and sys.stdout.write() are not intended to be used with each other.

Luckily it looked like the latter on further debugging. Corrected the code and it worked.

Here is the correct code to send Binary Data over FastCGI.

import sys
import os
os.write(sys.stdout.fileno(), bytes("Content-Type: image/png\r\n\r\n", "utf-8"));
f = open("/tmp/WebPython-128px.png", "rb");
d = f.read();
n=os.write(sys.stdout.fileno(), d );



And, here's the proof.

The Image BTW is WebPython's Logo.

Comments

Popular Posts