ImportCSV fromDjango.httpImportHttpResponse#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]defunruly_passengers_csv (Request):
#Create the HttpResponse object with the appropriate CSV header.Response = HttpResponse (mimetype='Text/csv') #告诉浏览器, the returned document is a CSV file response['content-disposition'] ='attachment; Filename=unruly.csv' #响应会有一个附加的content-disposition header, which contains the file name of the CSV file #Create The CSV writer using the HttpResponse as the "file."writer =Csv.writer (response) Writer.writerow ([' Year','Unruly Airline passengers']) #调用writer.writerow and pass it to an iterative object such as a list or a tuple that can be written to a row in a CSV file for(year, NUM)inchZip (Range (1995, 2006), unruly_passengers): Writer.writerow ([year, Num])returnResponse
The CSV module operates on objects that are similar to files, so you can use HttpResponse to replace
Django generates a CSV file