Note to self, when handling CGI file uploads on a Windows machine, you need the following boiler plate to properly handler binary files.

try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

Also, if you’re handling very large files and don’t want to eat up all your memory saving them using the copyfileobj method, you can use a generator to buffer read and write the file.

def buffer(f, sz=1024):
    while True:
        chunk = f.read(sz)
        if not chunk: break
        yield chunk
# then use it like this ...
for chunk in buffer(fp.file)

Leave a Reply

You must be logged in to post a comment.