将curl转换为python3,将image转换为base64不起作用

2024-04-25 05:05:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个curl命令,它正在将转换为base64的jpg图像发送到web服务:

curl -X POST --insecure \
https://link_to_the_web_service.com \
-H 'authorization:authorization_token'  \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{"model_spec": {"name": "inception", "signature_name": "predict_images"}, "inputs": {"images": {"dtype": 7, "tensor_shape": {"dim":[{"size": 1}]}, "string_val": ["IMAGE_CONVERTED_TO_BASE_64"]}}}'

我正在使用以下网站将jpg图像转换为base64:“https://www.browserling.com/tools/image-to-base64”。curl命令的执行给出了一个成功的输出。你知道吗

现在,我通过拍摄jpg图像来测试web服务,使用python3将curl命令转换为python3,将图像转换为base64,如下所示:

import requests
import base64

host = 'https://link_to_the_web_service.com'
image = 'sample5.jpg'

image_64_encode = base64.b64encode(open('sample5.jpg',"rb").read())

headers = {'authorization': token, 'cache-control': 'no-cache', 'content-type': 'application/json'}

data={"model_spec": {"name": "inception", "signature_name": "predict_images"}, "inputs": {"images": {"dtype": 7, "tensor_shape": {"dim":[{"size": 1}]}, "string_val": [str(image_64_encode)]}}}

request = requests.post(url=host, 
                    data=data,
                    headers=headers,
                    verify=False)

print(request)

我收到一个<;500>;响应,这意味着web服务无法读取图像输入。 我甚至尝试了“base64.encodestring”转换成base64,但没有成功。你知道吗

如何正确地将上述curl命令转换为python?你知道吗


Tags: tonamehttps图像image命令comweb
1条回答
网友
1楼 · 发布于 2024-04-25 05:05:10

requests.post方法的data参数需要一个字符串,而不是dict。您应该使用json参数将负载作为JSON发布:

request = requests.post(url=host, 
                        json=data,
                        headers=headers,
                        verify=False)

相关问题 更多 >