Skip to content Skip to sidebar Skip to footer

Output Binary Data From Cgi In Python 3

This question is related to this one. I was having no problems while printing raw binary data from a CGI script in Python 2, for example: #!/usr/bin/env python2 import os if __na

Solution 1:

Use sys.stdout.flush to force the header printed before the body:

import os
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        print("Content-Type: image/png\n")
        sys.stdout.flush() # <---
        sys.stdout.buffer.write(f.read())

Or remove print, and use sys.stdout.buffer.write only:

import os
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        sys.stdout.buffer.write(b"Content-Type: image/png\n\n") # <---
        sys.stdout.buffer.write(f.read())

NOTE

f.read() could cause a problem if the file is huge. To prevent that, use shutil.copyfileobj:

import os
import shutil
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        sys.stdout.buffer.write(b"Content-Type: image/png\n\n")
        shutil.copyfileobj(f, sys.stdout.buffer)

Post a Comment for "Output Binary Data From Cgi In Python 3"