首页 > 解决方案 > 结果:失败异常:TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'dict'

问题描述

我在这个作业中遇到问题,我正在发送一个带有编码图像 base64 作为邮递员中的 json 对象的发布请求。我应该解码 json 正文并将其保存为 azure blob 存储上的图像。我成功地将 blob 创建为 txt,但这次我运气不佳。任何帮助都感激不尽

结果:失败异常:TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'dict'

在此处输入图像描述

标签: pythonazure

解决方案


如果要使用 Azure 函数将图像文件上传到 Azure blob 存储,可以尝试使用将form图像发送到 Azure 函数。例如

  1. 在中添加存储连接字符串local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "ConnectionString" : "",
    "ContainerName": ""
  }
}

  1. 代码
import logging
import os
import azure.functions as func
from azure.storage.blob import BlobServiceClient, BlobClient
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        file=  req.files.get('the key value in your form')
        logging.info(file.filename)
        
        connect_str=os.environ["ConnectionString"]
        container=os.environ["ContainerName"]
        
        blob_service_client = BlobServiceClient.from_connection_string(connect_str)
        blob_client =blob_service_client.get_blob_client(container=container,blob=file.filename)
        blob_client.upload_blob(file)
    except Exception as ex:
        logging.info(ex.args)
       
    return func.HttpResponse("ok")
    
  1. 在 Postman 中测试 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

更新

根据我的测试,如果我们使用base64.b64decode()解码,我们会得到字节对象。所以我们需要使用create_blob_from_bytes上传。例如

我的代码

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    # get image base64 string
    file=req.get_json()
    image=file['image'].replace(' ', '+')
    #decode base64 string
    data=base64.b64decode(image)
    logging.info(type(data))
    #upload
    block_blob_service = BlockBlobService(account_name='blobstorage0516', account_key='')
    container_name='test'
    blob_name='test.jpeg'
    block_blob_service.create_blob_from_bytes(container_name, blob_name, data)

  
    return func.HttpResponse(f"OK!")

在此处输入图像描述 在此处输入图像描述


推荐阅读