I am having trouble sending a file response using Azure Functions and FastAPI. I am able to get this to work in my local environment but that's using my local directory and not a temp directory in Azure.
I have a Linux consumption plan - the code below is what I have been trying to push. it builds fine but calling the API from my browser doesn't generate the file on the client side as a download.
@app.get("/get_csv", response_description='xlsx')
async def get_csv():
Simulation_results = {'Fleet Size': [10,10], "Expected Yearly Demand":[10,10],"Actuals":
[10,10], "Service Level":[10,10]}
df = pandas.DataFrame(data=Simulation_results)
tempFilePath = tempfile.gettempdir()
file_path = '/tmp/temp_excel.xlsx'
df.to_excel(file_path, index = False)
headers= {
'Content-Disposition': 'attachment; filename="filename.xlsx"'
}
return FileResponse(file_path, headers=headers)
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return func.AsgiMiddleware(app).handle(req, context)
I'm not too sure what I am doing wrong and any help will be much appreciated.
CodePudding user response:
i was finally able to get it to work by constructing the file path from tempfile.gettempdir()
corrected code below:
@app.get("/get_csv", response_description='xlsx')
async def get_csv():
headers= {
'Content-Disposition': 'attachment; filename="filename.xlsx"'
}
Simulation_results = {'Fleet Size': [10,10], "Expected Yearly Demand":
[10,10],"Actuals":[10,10], "Service Level":[10,10]}
df = pandas.DataFrame(data=Simulation_results)
fp = os.path.join(tempfile.gettempdir(), 'temp.xlsx')
df.to_excel(fp, index = False)
return FileResponse(fp, headers=headers)
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return func.AsgiMiddleware(app).handle(req, context)