一次性响应:HttpResponse类及其子类、JsonResponse类
流式响应:SteamingHttpResponse类、FileResponse类
文件下载为例
#HttpResponse方式,文件内容一次性响应,仅适合小文件 def file_download(request): with open('data.txt') as f: c=f.read() return HttpResponse(c)
#StreamingHttpResponse方式 def big_file_download(request): def file_iterator(file_name,chunk_size=512): with open(file_name) as f: while True: c=f.read(chunk_size) if c: yield c else: break fname="data.txt" response=StreamingHttpResponse(file_iterator(fname)) return response
#FileResponse方式 #FileResponse是StreamingHttpResponse的子类,自动分段、自动迭代、适合二进制文件传输 def homeproc2(request): cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) response=FileResponse(open(cwd + "/msgapp/templates/PyLogo.jpg","rb")) #指定文件类型 response['Content-type']='application/octet-stream' #指定文件名称 response['Content-Disposition']='attachment;filename="pylogo.jpg' return response
标签:视图,Django,响应,file,HttpResponse,response,def,FileResponse From: https://www.cnblogs.com/lag1/p/18045186