我的線沿線的一個觀點:的Django如何最好地解決Unicode的錯誤
def export(request, exportCSV):
if exportCSV:
...
# get a list of results named list
...
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=myfile.csv'
writer = csv.writer(response)
writer.writerow(['firstfield', 'secondfield', ... ,])
for item in list:
writer.writerow([item.firstfield, item.secondfield, ... ,])
return response
的問題是,某些字段包含西班牙語文本等領域引發以下錯誤:
'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)
現在,如果我追加.encode('utf8)
至得罪領域,一切都很好:
...
for item in list:
writer.writerow([item.firstfield.encode('utf8'), item.secondfield.encode('utf8'), ... ,])
然而,將此分配給每個字段明顯違反了DRY。另外,並非每個字段都接受這種編碼。如果我追加到一些領域我產生這個錯誤:
'int' object has no attribute 'encode'
或:
'NoneType' object has no attribute 'encode'
所以,我怎麼能與這第一個錯誤,同時確保字段不產生第二類錯誤的最好的交易?我應該甚至在視圖層面處理這個問題,還是可以在模型中處理?
http://docs.python.org/library/csv.html#examples,有一個unicode_csv_reader的例子。你也可以捕獲UnicodeDecodeError(或者你看到的w/e錯誤)並且適當地對文本字段進行編碼。 – dm03514 2012-01-05 21:09:02
hmm。我嘗試過使用UnicodeWriter類,但仍然遇到相同的錯誤。 – 2012-01-06 00:30:25