Azure Function Python: 返回 Blob 对象内容
这是一个使用 Python 编写的 Azure Function 示例,用于获取指定路径下的 Blob 对象并返回其内容:
import logging
import azure.functions as func
from azure.storage.blob import BlobServiceClient
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# 获取请求参数中的路径
path = req.params.get('path')
if not path:
try:
req_body = req.get_json()
except ValueError:
pass
else:
path = req_body.get('path')
# 如果路径为空,返回错误响应
if not path:
return func.HttpResponse(
'Please pass a path on the query string or in the request body',
status_code=400
)
# 连接Blob服务并获取指定路径下的Blob对象
connection_string = '<your-storage-account-connection-string>'
container_name = '<your-container-name>'
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(path)
# 返回Blob对象的内容
blob_content = blob_client.download_blob().content_as_text()
return func.HttpResponse(blob_content)
在运行此 Azure Function 之前,需要先安装 Azure Functions 的 Python 库和 Azure Storage Blob 库:
pip install azure-functions
pip install azure-storage-blob
在 Azure Portal 中创建一个 HTTP 触发器的 Azure Function,将上面的代码复制粘贴到函数代码编辑器中,然后保存并运行该函数。在浏览器中访问该函数的 URL,并在查询参数中指定路径,即可返回该路径下的 Blob 对象的内容。
原文地址: https://www.cveoy.top/t/topic/oLFi 著作权归作者所有。请勿转载和采集!