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

时间:2020-03-23 04:15:07

标签: python azure

我在做这个作业时遇到了问题,我在其中发送一个带有编码图像base64的发布请求作为postman中的json对象。我应该对json主体进行解码,然后将其另存为azure blob存储中的图像。我已经成功地将blob创建为txt,但是这次我没有太多运气。任何帮助将不胜感激

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

enter image description here

2 个答案:

答案 0 :(得分:0)

如果要使用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. 邮递员测试 enter image description here enter image description here enter image description here

更新

根据我的测试,如果我们使用base64.b64decode()进行解码,则会得到bytes对象。因此,我们需要使用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!")

enter image description here enter image description here

答案 1 :(得分:0)

这是我发送POST请求的方式,需要在我的函数应用中处理。我可以成功创建Blob,但是从Blob中只能从URL中获取损坏的图像。enter image description here