【问题标题】:Result: Failure Exception: TypeError: argument should be a bytes-like object or ASCII string, not 'dict'结果:失败异常:TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'dict'
【发布时间】:2020-03-24 15:02:51
【问题描述】:

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

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

【问题讨论】:

  • 请编辑您的问题并包含实际代码,而不是粘贴代码的屏幕截图。
  • 请提供minimal reproducible example。不要不要发布代码图片。将您的代码发布为格式化文本See here 获取有关您问题中的代码格式的一些信息。

标签: python azure


【解决方案1】:

如果您想使用 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()进行解码,我们会得到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!")

【讨论】:

  • 感谢您的回复,但我需要将图像作为编码的 base64 throw postman 发送。
【解决方案2】:

这就是我发送 POST 请求的方式,需要在我的函数应用程序中进行处理。我成功地创建了 blob,但我只在 blob 的 url 中得到了一个损坏的图像。enter image description here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2018-03-17
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多