How to Create CSV File download with Azure Function in Python

Question:

I am trying to write an Azure Function that fetches data from a WebAPI, and returns a CSV file as a download to the user who enters the Function URL.

The CSV file is already successfully created and downloaded.

This is solved with the following code:

import logging

import azure.functions as func

from init_iterateNodeUserHomeAdress import createCSV


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

        
    #Geneartion CSV String
    csv=createCSV()
    
    
    
    #Converting String to CSV File
    filebytes= bytes(csv, 'utf-8')
    #Returning CSV file
    return func.HttpResponse(body=filebytes, status_code=200, mimetype='application/octet-stream')

The problem is that the file that is downloaded has the name of the HttpTrigger and no file extension.

I would like the downloaded file to have the name
report.csv.
Does anyone here have a solution?

Translated with www.DeepL.com/Translator (free version)

Asked By: Haggy2k3

||

Answers:

Try by setting Content-Disposition response header.

Something like:

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

        
    #Geneartion CSV String
    csv=createCSV()
    
    
    
    #Converting String to CSV File
    filebytes= bytes(csv, 'utf-8')
    #Returning CSV file
    headers = {
      "Content-Disposition": "attachment; filename='report.csv'"
    }
    return func.HttpResponse(body=filebytes, status_code=200, headers=headers, mimetype='application/octet-stream')
Answered By: Gaurav Mantri