[英]How to dynamically set the output name for a blob in azure functions for python
I created an azure function in Python that gets triggered after a blob upload happens.我在 Python 中创建了一个 azure function,它在 Blob 上传发生后触发。 I would like to copy and rename the blob to another storage.
我想将 blob 复制并重命名为另一个存储。 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!谢谢!
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.尝试使用 blob 的Input stream名称参数替换
blob_name
。
REFERENCES: Dynamic rename Azure Blob if already uploaded参考: 动态重命名 Azure Blob(如果已上传)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.