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)