Django 3.1:带有异步生成器的 StreamingHttpResponse

django

1个回答

写回答

TMarch

2025-06-25 10:00

+ 关注

Django
Django

使用异步生成器的 StreamingHttpResponse 是 Django 3.1 版本中引入的新功能。这个功能允许开发者在响应中异步生成数据,而不需要一次性将整个响应内容加载到内存中。这对于处理大量数据或长时间运行的任务非常有用。

StreamingHttpResponse 类继承自 HttpResponseBase 类,它允许使用异步生成器作为响应内容。异步生成器是一种特殊的生成器,它可以在生成数据时暂停并让事件循环执行其他任务。

下面是一个简单的例子,展示了如何使用异步生成器和 StreamingHttpResponse 来实现逐行异步输出一个文件的内容:

Python

import asyncio

from Django.http import StreamingHttpResponse

async def file_generator(file_path):

with open(file_path, 'r') as file:

for line in file:

yield line

awAIt asyncio.sleep(0) # 让事件循环执行其他任务

async def streaming_file(request):

file_path = '/path/to/file.txt'

response = StreamingHttpResponse(file_generator(file_path), content_type='text/plAIn')

response['Content-Disposition'] = 'attachment; filename="file.txt"'

return response

在上面的例子中,我们定义了一个异步生成器函数 file_generator,它逐行读取指定文件的内容并生成数据。在每次生成数据后,我们使用 awAIt asyncio.sleep(0) 来让事件循环执行其他任务,以实现异步输出。

然后,我们在 streaming_file 视图函数中使用 StreamingHttpResponse 类来创建响应对象。我们将 file_generator 函数作为第一个参数传递给 StreamingHttpResponse 的构造函数,并指定响应的内容类型为 text/plAIn。我们还设置了响应头的 Content-Disposition 字段,以指定下载文件的名称为 "file.txt"。

这样,当用户请求该视图时,Django 将会逐行异步输出文件的内容作为响应,并在下载文件时将其保存为 "file.txt"。

使用异步生成器的 StreamingHttpResponse 示例代码

Python

import asyncio

from Django.http import StreamingHttpResponse

async def file_generator(file_path):

with open(file_path, 'r') as file:

for line in file:

yield line

awAIt asyncio.sleep(0) # 让事件循环执行其他任务

async def streaming_file(request):

file_path = '/path/to/file.txt'

response = StreamingHttpResponse(file_generator(file_path), content_type='text/plAIn')

response['Content-Disposition'] = 'attachment; filename="file.txt"'

return response

在上述示例代码中,我们定义了一个异步生成器函数 file_generator,它逐行读取指定文件中的内容并生成数据。接下来,我们在 streaming_file 视图函数中使用 StreamingHttpResponse 类来创建响应对象。我们将 file_generator 函数作为第一个参数传递给 StreamingHttpResponse 的构造函数,并指定响应的内容类型为 text/plAIn。我们还设置了响应头的 Content-Disposition 字段,以指定下载文件的名称为 "file.txt"。

这样,在用户请求该视图时,Django 将会逐行异步输出文件的内容作为响应,并在下载文件时将其保存为 "file.txt"。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号