输出CSV文件以供下载,而不将CSV保存在服务器中



我正在开发一个api端点,该端点将使用Python的Fast api框架供公众使用。它已经完成并工作了,但它的工作方式是我将创建它,然后保存到服务器的本地目录,然后读取该文件并返回一个csv文件作为对用户的响应。

我的问题是,如何直接将csv文件返回给用户,而不将其保存在服务器的目录中。我的代码现在是这样的

def export_client_invoice(client_id):
invoice_doc = client_docs_db.view("client_invoice/by_client_id", key=int(client_id), include_docs=True)
data = ["value %d" % i for i in range(1,4)]
with open("./file.csv", 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(data)
file_like = open("./file.csv", mode="rb")
response = StreamingResponse(file_like, media_type="text/csv")
response.headers["Content-Disposition"] = "attachment; filename=export.csv"

return response

我无法用fastapi测试它,所以您可能需要采用一些方法才能使它在您的上下文中工作。

from io import BytesIO
import csv
import codecs
data = ['value %d' % i for i in range(1,4)]
StreamWriter = codecs.getwriter('utf-8')
file_like = StreamWriter(BytesIO())
wr = csv.writer(file_like, quoting=csv.QUOTE_ALL)
wr.writerow(data)
print(file_like.getvalue())
# b'"value 1","value 2","value 3"rn'
response = StreamingResponse(file_like, media_type="text/csv")

@jackhammer013,您可以使用此代码返回带有FastAPI 的csv文件

from fastapi.responses import StreamingResponse
... 
return StreamingResponse(iter([file_like.getvalue()]),
status_code=status.HTTP_200_OK,
headers={
"Content-Disposition": f"attachment; filename=test.csv"
},
media_type="text/csv")

最新更新