繁体   English   中英

使用 Azure 函数中的 Python 根据 Azure Blob 存储中的模式匹配检查 Blob 是否存在

[英]Check Existence of Blob based on Pattern match in Azure Blob Storage using Python in Azure Functions

有没有办法根据使用 Azure Function 的模式使用 Python 检查文件是否存在于 Azure BLOB 容器中? 我有不同的文件传入,我需要根据“文件名”参数处理它们。 放在容器上的文件将带有附加日期。 我需要检查文件是否存在,然后处理它。

容器中的示例文件 =>

  1. API_File1_20202008.CSV

  2. API_File2_20202008.CSV

  3. API_File3_20202008.CSV

如果参数传入 Function => API_File1.
然后 function 应该检查指定的 API_File1* 中是否存在任何 blob,然后处理。

对于本地操作系统,我能够使用以下内容。

for name in glob.glob(SourceFolder +'/' + FileName + '*.CSV'):
    print(name)

有什么建议吗?

对于这个需求,可以使用下面的代码在azure上实现。

import logging

import azure.functions as func
from azure.storage.blob.blockblobservice import BlockBlobService


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

    #just focus on below part
    block_blob_service = BlockBlobService(account_name="<your storage name>", account_key="<storage key>")

    if block_blob_service.exists("<container name>", "file5.csv"):
            print("========found file=======");
    else:
            print("========not exist========");
    #just focus on the part above

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

在运行代码之前,您需要安装模块。 不要安装pip install azure-storage-blob ,我测试了 install azure-storage-blob但它出现了一些问题。 你可以在“终端”window你的虚拟环境中安装pip install azure==4.0.0 (可能需要一些时间),然后代码就可以运行成功了。

===================================更新============== ====================

我认为我们不能直接通过"File5" + "*.CSV" .CSV”来查询文件名。 但我可以提供一个解决方法供您参考。 然后function获取请求参数fileName然后使用下面的代码:

files = [blob for blob in block_blob_service.list_blobs("testcontainer") if blob.name.startswith(fileName)]

for file in files:
    logging.info(file.name)

该代码用于获取以您发送到fileName的文件名开头的所有文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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