I am working on a api end-point that will be available for public use using Python's Fast API framework. It is already done and working but the way it works is I will create it, then save to the local directory of the server then read that file and return a csv file as a response to the user.
My question is, how do I just return the csv file directly to the user without saving it in the server's directory. My code is like this right now
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