tags:

views:

136

answers:

2

this is my test code:

def test_import_data(self):
       f = open('commend/fixtures/Book2.xls')
       postdata = {'datatype':'intonetwork','datafile':f}
       response = self.client.post('/commend/saledata/import_data/',postdata)
       self.failUnlessEqual(response.status_code, 200)

but in the view code:

file = request.FILES['datafile']
size = file.size

the size only equal 6.

so i debug the Client.post code:

def encode_file(boundary, key, file):
   to_str = lambda s: smart_str(s, settings.DEFAULT_CHARSET)
   return [
       '--' + boundary,
       'Content-Disposition: form-data; name="%s"; filename="%s"' \
           % (to_str(key), to_str(os.path.basename(file.name))),
       'Content-Type: application/octet-stream',
       '',
       file.read()
   ]

when i open the commend/fixtures/Book2.xls.

>>> f = open("commend/fixtures/Book2.xls")
>>> f.read()

'\xd0\xcf\x11\xe0\xa1\xb1'

>>> f.read()

'\x00\xb9\xa4\xd7\xf7\xb1\xed\x00\x03\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x01\x00\xfe\xff\x03\n\x00\x00\xff\xff\xff\xff \x08\x02\x00\x00 \x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00F#\x00\x00\x00Microsoft Office Excel 200 3 \xb9\xa4\xd7\xf7\xb1\xed\x00\x06\x00\x00\x00Biff8\x00\x0e\x00\x00\x00Excel.She et.8\x00\xf49\xb2q\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x ........................

when type f.read() for the first time,output '\xd0\xcf\x11\xe0\xa1\xb1',not the entire xls document content.

How can I do?

A: 

Try opening the file in binary mode:

f = open('commend/fixtures/Book2.xls', 'rb')
Daniel Roseman
A: 

I think that's being read in Unicode. Just for testing, try to save the xls file in other format and see what happens. Here the issues with Unicode in python are exposed.

yeyeyerman