CGI python 3 write RAW BINARY

sam samuelrobertson at gmail.com
Fri May 21 05:23:09 EDT 2010


On May 7, 7:33 am, Dodo <dodo_do_not_wake... at yahoo.Fr> wrote:
> Le 01/05/2010 12:52, Dodo a écrit :
>
>
>
>
>
> > 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 )
>
> > Dorian
>
> Anyone?

Yes for windows you need to call this before you write it out.  And
yes its totally retarded that you have to do this.  The whole point of
python is that I don't have to worry about the particular system its
running on.

 def __SetStdOutForWindowsToBinaryMode():
        # Without this method a windows server will translate '\n'
into '\r\n'
        # even for binary output.  This probably isn't needed on linux
servers
        # so the exception will be caught harmlessly.
        # At some point we may have to worry about switching this mode
*back* to original
        # (see http://bytes.com/topic/python/answers/30987-cgi-proplem-displaying-image)
        try:
            import msvcrt,os
            msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for
stdin
        except ImportError:
            pass





More information about the Python-list mailing list