Below is my React code to retrieve the .csv
file. I would like the file to be downloaded immediately on click of the button:
downloadData = () => {
fetch('http://localhost:8000/genreport')
.then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'onomonitoring.csv';
a.click();
});
...
render() {
return (
<div id="container">
<button onClick={this.downloadData}>Download</button>
</div>
)
}
}
This is my FastAPI code to generate the .csv
file:
@app.post("/genreport")
def gen_colreport(db: Session = Depends(get_db)):
df = collection_report(db)
date_today = datetime.today().strftime('%Y%m%d')
col_report_str = "collectionreport_"
filename = col_report_str + date_today + ".csv"
# col_report = df.to_csv(filename, encoding="utf-8")
stream = io.StringIO()
df.to_csv(stream, encoding="utf-8", index= False)
response = StreamingResponse(iter([stream.getvalue()]),
media_type="text/csv"
)
response.headers["Content-Disposition"] = "attachment; filename=%s" % (filename)
return response
I can download the file from FastAPI but when I run the code it throws a 405 Method Not Allowed
error. Is there a way I can download the .csv
file from FastAPI directly or retrieve the csv file from the database directly?