Home > Mobile >  How to Create CSV File download with Azure Function in Python
How to Create CSV File download with Azure Function in Python

Time:08-15

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)

CodePudding user response:

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')
  • Related