【问题标题】:convert curl to python3 and image to base64 not working将 curl 转换为 python3 并将图像转换为 base64 不起作用
【发布时间】:2019-02-27 20:21:46
【问题描述】:

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

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 图像、将 curl 命令转换为 python3 并使用 python3 将图像转换为 base64 来测试 Web 服务,如下所示:

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)

我收到 响应,这意味着 Web 服务无法读取图像输入。 我什至尝试将 'base64.encodestring' 转换为 base64,但没有成功。

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

【问题讨论】:

    标签: python python-3.x curl python-requests base64


    【解决方案1】:

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

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

    【讨论】:

    • 我尝试使用 json 参数。它仍然是 响应。
    • 我将文件作为字节输入而不是字符串输入发送并且它有效。
    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 2014-04-06
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多