jjlee / mechanize

Stateful programmatic web browsing in Python, after Andy Lester's Perl module WWW::Mechanize .
http://wwwsearch.sourceforge.net/mechanize/
618 stars 121 forks source link

No way to give data as bytes to FileControl #26

Closed turadg closed 14 years ago

turadg commented 14 years ago

FileControl assumes that the data to include in the field of the form comes from a file on disk. It should also allow adding a file from a byte array source.

In most environments there's an easy work-around for the current limitation, just write a temporary file. Unfortunate Google AppEngine doesn't allow writing files. (And I want to take data from a db.Blob and upload it to a web form.)

If there's another workaround I haven't thought of please let me know. Maybe a proxy class that works enough like File but is sourced with a byte array?

turadg commented 14 years ago

Ok, I should have investigated more before filing an issue. Simple work-around is:

class FileLike():

    def __init__(self, data):
        self.data = data

    def read(self):
        return self.data

I'll post this instead of deleting the ticket in case anyone else encounters the same difficulty.

Still I wonder, why take file_object instead of the data itself? So it doesn't sit in memory between add_file() and the post?

jjlee commented 14 years ago

With a file object, the implementation doesn't need to read the whole file into memory (though apparently it does read it all ATM -- odd, thought I'd fixed that ages ago).

The standard Python idiom is to use module StringIO rather than a throwaway class like the one you paste above (I usually "import cStringIO as StringIO").