使用aiohttp将数据作为文件发送

2024-10-01 07:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的端点,它返回带有csv的文件:

# POST /export/
@asyncio.coroutine
def export(request):
    post = yield from request.post()
    if not post.get('passwd', None) == 'topsecret':
        return web.Response(status=403)

    csv = data.encode()
    resp = web.StreamResponse(headers=aiohttp.MultiDict({
        'CONTENT-DISPOSITION': 'attachment; filename="%d.csv"' % int(time.time())}))
    resp.content_type = 'text/csv'
    resp.content_length = len(csv)
    yield from resp.prepare(request)

    resp.write(csv)

    return resp

下一个问题是:是否可以自动设置标题?正如documentation所说,aiohttp有BodyPartWriter类,它有set_content_disposition方法。但是,据我所知,它只能用于客户机API(或者至少,只有客户机API的示例)。 那么,是否可以将BodyPartWriterResponse对象一起使用?在


Tags: csvfromweb客户机returnaiohttptimeresponse
1条回答
网友
1楼 · 发布于 2024-10-01 07:45:30

^{}&;^{}API仅用于读取或写入一个多部分编码的客户端请求/响应的一部分(因此,它们在multipart模块下)。在

发送一个多部分服务器端响应没有任何意义。在

在您的例子中,您将返回一个响应,提供content-disposition作为对浏览器如何命名文件的提示。目前还没有自动发送文件的方式来填充相应的头文件。在

相关问题 更多 >