【问题标题】:How to dynamically set the output name for a blob in azure functions for python如何在 python 的 azure 函数中动态设置 blob 的输出名称
【发布时间】:2021-12-30 14:09:57
【问题描述】:

我在 Python 中创建了一个 azure 函数,该函数在 Blob 上传发生后触发。 我想将 blob 复制并重命名为另一个存储。这就是我现在拥有的:

// 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())

这工作正常,但它只复制文件。如何在运行时动态重命名文件?

谢谢!

【问题讨论】:

  • 请问为什么要在运行时动态重命名文件?
  • 这只是一个小例子。上传新文件时会触发我的函数。此文件包含 CSV 数据。基于该数据,我进行了一些计算,我想将结果存储在一个新文件中。由于文档指出,天蓝色的函数也支持向外的方向,我想知道我是否可以将它用于这样的目的。简而言之:一个文件上传到“ingress/upload/{name}”,我想在“ingress/upload{newName}”中存储一个计算结果的新文件。

标签: python python-3.x azure-functions


【解决方案1】:

随着文件被复制,现在您可以使用下面提到的解决方法之一更改复制的文件。

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)

尝试使用 blob 的 Input stream 名称参数替换 blob_name

参考: Dynamic rename Azure Blob if already uploaded

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2016-07-25
    • 1970-01-01
    • 2020-09-12
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多