简体   繁体   中英

How to Create CSV File download with Azure Function in Python

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM