广西东晋建设有限公司网站,电商详情页模板免费套用,湖南网站建设磐石网络答疑,做网站的企业广州锋哥原创的Python Web开发 Django5视频教程#xff1a;
2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计25条视频#xff0c;包括#xff1a;2024版 Django5 Python we…锋哥原创的Python Web开发 Django5视频教程
2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计25条视频包括2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~、第2讲 Django5安装、第3讲 Django5创建项目(用命令方式)等UP主更多精彩视频请关注UP账号。https://www.bilibili.com/video/BV14Z421z78C/响应内容除了返回网页信息外还可以实现文件下载功能是网站常用的功能之一。
Django提供三种方式实现文件下载功能分别是HttpResponse、StreamingHttpResponse和 FileResponse,三者的说明如下: HttpResponse是所有响应过程的核心类它的底层功能类是HttpResponseBase。 StreamingHttpResponse是在 HttpResponseBase的基础上进行继承与重写的它实现流式响应输出流式响应输出是使用Python的迭代器将数据进行分段处理并传输的)适用于大规模数据响应和文件传输响应。 FileResponse是在StreamingHttpResponse 的基础上进行继承与重写的它实现文件的流式响应输出只适用于文件传输响应。
我们通过实例来看下如何应用
我们准备一个文件这里我们用一个exe二进制文件。放D盘根目录。 views.py里写方法实现方法
# 定义文件路径
file_path D:\\360zip_setup.exedef download_file1(request):file open(file_path, rb) # 打开文件response HttpResponse(file) # 创建HttpResponse对象response[Content_Type] application/octet-streamresponse[Content-Disposition] attachment;filenamefile1.exereturn responsedef download_file2(request):file open(file_path, rb) # 打开文件response StreamingHttpResponse(file) # 创建StreamingHttpResponse对象response[Content_Type] application/octet-streamresponse[Content-Disposition] attachment;filenamefile2.exereturn responsedef download_file3(request):file open(file_path, rb) # 打开文件response FileResponse(file) # 创建FileResponse对象response[Content_Type] application/octet-streamresponse[Content-Disposition] attachment;filenamefile3.exereturn response
urls.py里定义下映射
path(download1, helloWorld.views.download_file1),path(download2, helloWorld.views.download_file2),path(download3, helloWorld.views.download_file3)
为了方便测试我们static目录下新建一个download.html静态文件
!DOCTYPE html
html langen
headmeta charsetUTF-8title下载测试/title
/head
body
a href/download1下载测试一HttpResponse/abr
a href/download2下载测试二StreamingHttpResponse/abr
a href/download3下载测试三FileResponse/a
/body
/html
页面输入http://127.0.0.1:8000/static/download.html 测试 分别点击下载测试