0

I created an azure function in Python that gets triggered after a blob upload happens. I would like to copy and rename the blob to another storage. This is what I have right now:

// function.json
{
  "scriptFile": "main.py",
  "bindings": [
  {
    "name": "myblob",
    "type": "blobTrigger",
    "direction": "in",
    "path": "ingress/upload/{name}",
    "connection": "conn_STORAGE"
  },
  {
    "name": "myblobout",
    "type": "blob",
    "direction": "out",
    "path": "ingress/test/{name}",
    "connection": "conn_STORAGE"
  }]
}
# main.py
import logging
import azure.functions as func


def main(myblob: func.InputStream, myblobout: func.Out[bytes]):
    myblobout.set(myblob.read())

This works fine but it only copies the file. How can I rename the file dynamically during runtime?

Thx!

Maecky
  • 1,988
  • 2
  • 27
  • 41
  • May I Know why do you want to rename the file dynamically during runtime? –  Dec 27 '21 at 07:21
  • This was just a small example. My function gets triggered when a new file is uploaded. This file contains CSV data. Based on that data I do some calculations and I want to store the results in a new file. Since the documentation states, that azure functions do also support a out direction I was wondering if I could use it for such a purpose. In short: a file is uploaded to "ingress/upload/{name}" and I want to store a new file with calculated results in "ingress/upload{newName}". – Maecky Jan 10 '22 at 06:40

1 Answers1

0

As the file gets copied, Now you can change the copied file using one of the workarounds mentioned below.

from azure.storage.blob import ContainerClient
from azure.core.exceptions import ResourceExistsError



blob_name = "abcd.zip"
container_client = ContainerClient.from_connection_string(conn_str, "container_name")
try:
blob_client = container_client .get_blob_client(blob_name)
# upload the blob if it doesn't exist
blob_client.upload_blob(data)
except ResourceExistsError:
# check the number of blobs with the same prefix.
# For example, This will return a generator of [abcd, abcd(1), abcd(2)]
blobs = list(container_client.list_blobs(name_starts_with=blob_name))
length = len(blobs)
if length == 1:
# it means there is only one blob - which is from the previous version
blob_client.upload_blob(data, overwrite=True)
else:
# if there are 10 files with the name starting with abcd, it means your name for the 11th file will be abcd(10).
name = blob_name.split('.')[0] + '(' + str(length) + ').' + a.split('.')[1]
blob_client = container_client .get_blob_client(blob_name)
blob_client.upload_blob(data)

Try replacing the blob_name using Input stream name parameter of the blob.

REFERENCES: Dynamic rename Azure Blob if already uploaded