Home > Net >  Azure Functions outputting JSON set filename?
Azure Functions outputting JSON set filename?

Time:01-09

I am creating an Azure function that outputs a json file to my blob storage. Below is the code located within my init.py file:

import json
import random
import requests
import azure.functions as func

cities = ["London", "Bath", "York", "Canterbury", "Oxford", "Durham", "Salisbury", "Liverpool", "Brighton", "Bristol", "Cambridge", "Manchester", "Nottingham", "Dover", "Birmingham", "Hastings"]

def main(req: func.HttpRequest, outputBlob: func.Out[str]) -> func.HttpResponse:
    url = "https://randomuser.me/api/"
    response = requests.get(url)
    data = response.json()
    first_name = data['results'][0]['name']['first']
    last_name = data['results'][0]['name']['last']
    dob = data['results'][0]['dob']['date']
    email = data['results'][0]['email']
    random_name = f"{first_name} {last_name}"
    random_city = random.choice(cities)
    global random_id
    random_id = random.randint(1, 10000)
    output_data = {
        "name": random_name,
        "dob": dob,
        "email": email,
        "city": random_city,
        "id": random_id
    }
    data_str = json.dumps(output_data)
    outputBlob.set(data_str, file_name=f"{random_id}.json")

    return func.HttpResponse(data_str, status_code=201)

Additionally, here is what is written in my function.json file:

{
  "bindings": [
    {
        "authLevel": "anonymous",
        "type": "httpTrigger",
        "direction": "in",
        "name": "req",
        "methods": ["get","post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "name": "outputBlob",
      "direction": "out",
      "type": "blob",
      "path": "bronze/",
      "connection": "storageaccountstevendas_STORAGE"
    }
  ]
}

This deploys from VSCode to Azure Functions, but when I run it, I get the following error:

Result: Failure Exception: TypeError: set() got an unexpected keyword argument 'file_name' Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 458, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 701, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper result = function(**args) File "/home/site/wwwroot/HttpTrigger11/__init__.py", line 28, in main outputBlob.set(data_str, file_name=f"{random_id}.json")

All I am trying to do is have the function output json files with the file name the same as random_id, e.g. 8981.json. Any help would be greatly appreciated!

I've tried changing the path in my function.json file to be "bronze/{random_id}.json", but this spits out the following error:

No value for named parameter 'random_id'.

I tried assigning another global variable to be eqivalent to random_id, but this produced the same error

CodePudding user response:

The set function can't have the filename parameter , The parameter needs to be passed through function.json

CodePudding user response:

After reproducing from my end, one way to achieve this is to use ContainerClient rather than using output binding. For the demonstration purpose, I have used the below code in my Function app where I'm trying to upload data.

init.py

import logging
from azure.storage.blob import BlockBlobService
import azure.functions as func
import os

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

    account_name="<ACCOUNT_NAME>"
    account_key="<ACCOUNT_KEY>"
    sas="<SAS_TOKEN>"
    container_name = "<CONTAINER_NAME>"

    fileName="abc.txt"
    filedata="This is a sample file"
    blob_service_client = BlockBlobService(account_name,account_key,sas)

    blob_service_client.create_blob_from_text(container_name,fileName,filedata);

function.json

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

RESULTS:

storage account

enter image description here

  • Related