
正文
Django 文件下载功能
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
def file_download(request):
con= MySQLdb.connect(host='192.168.xxx.xxx',user='root',passwd='xxxx',db='test')
cursor = con.cursor()
query = "SELECT * FROM xxxx"
cursor.execute(query)
with open('xxxx.csv','w') as f:
writer = csv.writer(f)
for row in cursor.fetchall():
writer.writerow(row)
with open('xxxx.csv') as f:
c = f.read()
response = HttpResponse(c)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format('xxxx.csv')
return response
上述代码是django下载文件的功能。
因为我使用的是MYSQL 数据库,先连接数据库,打开并导出文件writer, 然后使用open,read,读出文件,后HTTPRESPONE将文件下载导出。






