On Wed, Apr 20, 2011 at 1:02 AM, Daniel Gerzo <dge...@gmail.com> wrote:

> On 20.4.2011 2:22, Julio Ona wrote:
>
>> Hi Daniel,
>>
>> you should see:
>> http://docs.python.org/library/bz2.html#module-bz2
>>
>> <http://docs.python.org/library/bz2.html#module-bz2>or
>> http://docs.python.org/library/gzip.html#module-gzip
>>
>
> Hello Juliom, thanks for reply.
>
> I have of course seen both of these before I sent the mail, unfortunately I
> couldn't figure out how to use it on my InMemoryUploadedFile object.
>
>  But basically you should import the compress function from the library
>> and use it.
>>
>> <http://docs.python.org/library/gzip.html#module-gzip>from bz2 import
>>
>> compress
>>
>> [...]
>>
>>
>> def handle_uploaded_subtitles(self, files):
>>    for file in files:
>>        sub_file = SubtitleFile(file_name=file.name, etc)
>>        bz_file = compress(file)
>>
>
> I wish it would be that easy :-)
>
> What you are proposing fails with Exception:
>
> bzfile = compress(file)
> argument 1 must be convertible to a buffer, not InMemoryUploadedFile
>
>
Well, an InMemoryUploadedFile isn't a real file, so I'm not surprised that
that doesn't work. You'll have to pull the data out of it, and compress
that.

Try something like this:

def handle_uploaded_subtitles(self, files):
   for uploaded_file in files:
       sub_file = SubtitleFile(file_name=file.name, etc)
       data = bz2.compress(uploaded_file.read())
       # Here I'm assuming that SubtitleFile.file is a real file object
       sub_file.file.write(data)
       sub_file.file.close()

If your files are large, then you can read them in lines, or in chunks, and
use a BZ2Compressor object to compress them one-at-a-time.

Further, I wasn't able to find a method in the mentioned libraries that
> would make this possible, or at least I didn't figure out how to pass an
> InMemoryUploadedFile to them to compress it.
>
> When I try to do this:
>
> file.write(zlib.compress(file.read()))


Don't do that -- I'm pretty sure that writing a file that you already have
open for reading will produce undefined results.

(Also, I'd try to stay away from using 'file' as a variable name -- it just
hides the built-in file type name, and makes it hard to tell what, say,
file.read refers to)


-- 
Regards,
Ian Clelland
<clell...@gmail.com>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to