python - 结果:失败异常:TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'dict'
问题描述
我在这个作业中遇到问题,我正在发送一个带有编码图像 base64 作为邮递员中的 json 对象的发布请求。我应该解码 json 正文并将其保存为 azure blob 存储上的图像。我成功地将 blob 创建为 txt,但这次我运气不佳。任何帮助都感激不尽
结果:失败异常:TypeError:参数应该是类似字节的对象或ASCII字符串,而不是'dict'
解决方案
如果要使用 Azure 函数将图像文件上传到 Azure blob 存储,可以尝试使用将form
图像发送到 Azure 函数。例如
- 在中添加存储连接字符串
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "python",
"ConnectionString" : "",
"ContainerName": ""
}
}
- 代码
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")
更新
根据我的测试,如果我们使用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!")
推荐阅读
- r - R data.table 保留组的第一个非NA值直到组结束
- python - 如何解决 wget 下载的 403 错误
- react-native - 没有在 FlatList 上应用borderRadius
- python - 将年份和日期转换为 pandas 时间戳
- vb.net - csv 中的数据未正确对齐
- php - 以整数形式返回时间差
- postgresql - 自动增量不适用于序列类型的 ID 列
- python - 比较不同服务器中两个相似表之间的数据
- amazon-web-services - 将 IAM 角色从一个 EC2 传递到另一个 Ec2
- odoo - Changes in quants in Odoo 11 , 12