2009-08-12 194 views
0

這是我的測試代碼:單元測試

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) 

但在視圖代碼:

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

大小隻相當於6

,所以我調試客戶端.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() 
    ] 

當我打開通訊端/裝置/ Book2.xls中。

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

'\ XD0 \ XCF \ X11 \ xe0 \ XA1 \ XB1'

>>> f.read() 

「\ X00 \ xb9 \ XA4 \ XD7 \ XF7 \ XB1 \固定的\ 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 \ x00 \ x00 \ x00 \ 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 \固定的\ 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 \ x ..................... ...

第一次輸入f.read()時,輸出'\ xd0 \ xcf \ x11 \ xe0 \ xa1 \ xb1',而不是整個xls文檔內容。

我該怎麼辦?

回答

2

嘗試以二進制方式打開文件:

f = open('commend/fixtures/Book2.xls', 'rb') 
0

我認爲這在Unicode中被讀取。僅用於測試,請嘗試以其他格式保存xls文件並查看會發生什麼情況。 Here暴露了Python在Python中的問題。