Year,Unruly Airline Passengers 1995,146 1996,184 1997,235 1998,200 1999,226 2000,251 2001,299 2002,273 2003,281 2004,304 2005,203 2006,134 2007,147
備注
前面的列表包含真實數據。 這些數據來自美國 聯邦航空管理局。
CSV格式盡管看起來簡單,卻是全球通用的。 但是不同的軟件會生成和使用不同的 CSV 的變種,在使用上會有一些不便。 幸運的是, Python 使用的是標準 CSV 庫, csv ,所以它更通用。
因為 csv 模塊操作的是類似文件的對象,所以可以使用 HttpResponse 替換:
import csv from django.http import HttpResponse # Number of unruly passengers each year 1995 - 2005. In a real application # this would likely come from a database or some other back-end data store. UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203] def unruly_passengers_csv(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=unruly.csv' # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response
代碼和注釋可以說是很清楚,但還有一些事情需要特別注意:
在任何需要返回非 HTML 內容的時候,都需要經過以下幾步: 創建一個 HttpResponse 響應對象(需要指定特殊的 MIME 類型),它它傳給需要處理文件的函數,然后返回這個響應對象。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com