python - Python Django-如何在 django 项目中的客户端计算机上下载文件
问题描述
我是 python 新手,我创建了一个小型 Django 应用程序来将数据下载为 excel 格式。它下载到项目文件夹或给定路径(在服务器上)。
但是当我从客户端机器上点击 URL 时,它应该在客户端机器上下载,但它只在我的服务器上下载。请建议一种合适的方法(代码)来仅在客户端计算机上下载 excel 文件。
提前致谢。
- - - -代码 - - - -
try:
cursor = connection.cursor()
cursor.execute("""select * from table""")
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
result = len(data)
print("No of records :" ,len(data))
df = pd.DataFrame(list(data), columns=columns)
home = os.path.expanduser("~")
print('Home path------------',home)
download_location = os.path.join(home,'Downloads')
print('download path------------',download_location)
filename = 'django_simple.xlsx'
writer = pd.ExcelWriter(download_location+'/'+ filename)
df.to_excel(writer, sheet_name='Hundai')
writer.save()
print("File saved successfully!")
cursor.close()
except:
print("There is an error")
finally:
if (connection):
connection.close()
cursor.close()
print("The MSSQL connection is closed")
return render(request,'result.html',{'result': result})
解决方案
看看这个非常简单但有效的代码。
import pathlib
from django.http import FileResponse
def download(request):
file_server = pathlib.Path('the_path_of_your_file_to_download')
if not file_server.exists():
messages.error(request, 'file not found.')
else:
file_to_download = open(str(file_server), 'rb')
response = FileResponse(file_to_download, content_type='application/force-download')
response['Content-Disposition'] = 'inline; filename="a_name_to_file_client_hint"'
return response
return redirect('a_url_path')
推荐阅读
- react-native - 如何在 React Native 中为 ScrollView 的 backgroundColor 设置动画
- mysql - MySQL 从存储的 json 文档中提取多个嵌套值作为一个值
- c# - 在 AspNet (Core) 中验证后访问 ValidationResult 对象
- c# - WPF Kiosk 应用程序中的屏幕阅读器和屏幕键盘的辅助功能
- c - C99 浮点中间结果
- vba - VBA 字典运行时错误 1004
- javascript - 选择字符串并忽略空格
- java - Java套接字-如何将消息从客户端c1发送到服务器s,然后从s发送到客户端c2
- automation - 使用 Uipath 自动访问表单
- c# - C# Mvc Api Xml 无法在 Powershell 中将字符串转换为 XML