输出 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"\r\n'

response = StreamingResponse(file_like,media_type="text/csv")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...