如何使用Python中Azure功能的Azure Blob存储绑定将JSON数据上传到Azure存储Blob

问题描述 投票:0回答:1

我想使用Python中的Azure函数将JSON数据作为.json文件上传到Azure存储Blob。

因为我使用的是Azure Functions,而不是实际的服务器,所以我不想(并且可能无法)在本地内存中创建临时文件,并使用Azure Blob存储客户端库v2.1将文件上传到Azure blob存储, Python(reference link here)。因此,我想将输出Blob存储绑定用于Azure函数(reference link here)。

我正在使用HTTP触发器在Azure函数中对此进行测试。我通过输入Blob存储绑定(工作正常)来获取Azure Blob,对其进行处理,并通过上传一个覆盖它的新Azure Blob(我需要帮助)来对其进行更新。我的function.json文件看起来像这样:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "inputblob",
      "type": "blob",
      "path": "{containerName}/{blobName}.json",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "outputblob",
      "type": "blob",
      "path": "{containerName}/{blobName}.json",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

而且我的Python代码如下:

import logging
import azure.functions as func
import azure.storage.blob
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
import json, os

def main(req: func.HttpRequest, inputblob: func.InputStream, outputblob: func.Out[func.InputStream]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # Initialize variable for tracking any changes
    anyChanges= False

    # Read JSON file
    jsonData= json.loads(inputblob.read())

    # Make changes to jsonData (omitted for simplicity) and update anyChanges

    # Upload new JSON file
    if anyChanges:
        outputblob.set(jsonData)

    return func.HttpResponse(f"Input data: {jsonData}. Any changes: {anyChanges}.")

但是,这根本不起作用,并引发以下错误(screenshot):

值'func.Out'是不可订阅的

我想念什么?

python azure azure-functions azure-storage-blobs
1个回答
0
投票

您想要bytesstr,而不是InputStream,例如:

def main(inputblob: func.InputStream, outputblob: func.Out[bytes], context: func.Context):
    ...
    # Write to output blob
    outputblob.set(jsonData)

[InputStream represents an input blob

请参阅this sample中的strthis one中的bytes

© www.soinside.com 2019 - 2024. All rights reserved.