文件下载功能
相应内容除了返回网页的信息外,还可以实现文件的下载功能,Django提供三种下载文件的功能,分别是:HttpResponse,StreamingHttpResponse,FileResponse.
- HttpResponse:是所有响应过程的核心类,它的底层功能类是HttpResponseBase
- StreamingHttpResponse:是在HttpResponseBase的基础上进行继承和重写的,它实现流式响应输出(是使用python的迭代器将数据进行分段处理并输出)。适用于大型规模数据响应和文件传输响应
- FileResponse:是在StreamingHttpResponse的基础上继承重写的,它实现文件的流式响应输出,只适合用于文件传输和响应
class StreamingHttpResponse(HttpResponseBase): streaming = True def __init__(self, streaming_content=(), *args, **kwargs): super().__init__(*args, **kwargs) # `streaming_content` should be an iterable of bytestrings. # See the `streaming_content` property methods. self.streaming_content = streaming_content
- streaming_content:的数据格式可设为迭代器对象或字节流,代表数据或文件内容
- *args, **kwargs:设置HttpResponseBase的参数,即响应内容的数据格式,content_type和响应状态码status等参数。
若使用StreamingHttpResponswene实现文件下载,则文件以字节的方式读取,在StreamingHttpResponse实列化时传入文件的字节流,由于该类支持数据或文件内容的响应方式输出,因此还需设置响应内容的数据格式和文件下载格式。
class FileResponse(StreamingHttpResponse): """ A streaming HTTP response class optimized for files. """ block_size = 4096 def __init__(self, *args, as_attachment=False, filename='', **kwargs): self.as_attachment = as_attachment self.filename = filename