Django 文件下载功能

 1 def file_download(request):
 2     con= MySQLdb.connect(host='192.168.xxx.xxx',user='root',passwd='xxxx',db='test')
 3     cursor = con.cursor()
 4     query = "SELECT * FROM xxxx" 
 5     cursor.execute(query)
 6     with open('xxxx.csv','w') as f:
 7         writer = csv.writer(f)
 8         for row in cursor.fetchall():
 9             writer.writerow(row)
10     with open('xxxx.csv') as f:
11         c = f.read()
12     response = HttpResponse(c) 
13     response['Content-Type'] = 'application/octet-stream'
14     response['Content-Disposition'] = 'attachment;filename="{0}"'.format('xxxx.csv')
15     return response

 

上述代码是django下载文件的功能。

因为我使用的是MYSQL 数据库,先连接数据库,打开并导出文件writer, 然后使用open,read,读出文件,后HTTPRESPONE将文件下载导出。

posted @ 2015-08-24 15:59  西番莲果汁  阅读(244)  评论(0编辑  收藏  举报