首页 > 解决方案 > 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})

标签: pythondjangodjango-rest-framework

解决方案


看看这个非常简单但有效的代码。

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')

推荐阅读