簡體   English   中英

如何在 Python 中使用 Azure Functions 的 Azure Blob 存儲綁定將 JSON 數據上傳到 Azure 存儲 blob

[英]How to upload JSON data to Azure storage blob using Azure Blob storage bindings for Azure Functions in Python

我想使用 Python 中的 Azure 函數將 JSON 數據作為 .json 文件上傳到 Azure 存儲 blob。

因為我使用的是 Azure Functions 而不是實際的服務器,所以我不想(並且可能無法)在本地內存中創建臨時文件並使用適用於 Python 的 Azure Blob 存儲客戶端庫 v2.1 將該文件上傳到 Azure blob 存儲( 參考鏈接在這里)。 因此,我想對 Azure Functions 使用輸出 blob 存儲綁定( 參考鏈接在這里)。

我正在使用 HTTP 觸發器在 Azure Functions 中對此進行測試。 我通過輸入 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}.")

但是,這根本不起作用,拋出以下錯誤(截圖):

值 'func.Out' 是不可訂閱的

我錯過了什么?

您需要bytesstr ,而不是InputStream ,如下所示:

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

InputStream 表示輸入blob

這個樣本str這一次bytes

稍后更新:

json.loads()的調用返回一個字典,由於某種原因outputblob.set()了,需要一些處理,像這樣:

def main(req: func.HttpRequest,
         inputblob: func.InputStream,
         outputblob: func.Out[bytes]) -> func.HttpResponse:

    jsonData = json.loads(inputblob.read())
    outputblob.set(str(jsonData))

    return func.HttpResponse(f"Input JSON: {jsonData}")

這應該有效(它至少適用於func版本2.7.1948 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM