POST图片请求示例

最近更新时间: 2022-10-26 16:59:41

-- coding: utf-8 -- import base64
import hashlib
import hmac
import time
import os
import requests

secret_id = "AKIDmDJ4SUPSOz****" secret_key = "G9gAI3SUATQ0n****"

def get_string_to_sign(method, endpoint, params):
s = method + endpoint + "/?"
query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params))
return s + query_str

def sign_str(key, s, method):
hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest()
return base64.b64encode(hmac_str)

def image_to_string(image):
pic = open(image,'rb')
pic_base64 = str(base64.b64encode(pic.read()))
pic.close()
return pic_base64

if name == 'main':
endpoint = "contentsecurity.api3.yun.ccb.com"
data = {
'Action' : 'BspImageRecognition',
'Nonce' : 11886,
'FileContent' : image_to_string('simple'+os.sep+"dalai.jpg"),
'Region' : 'wh',
'SecretId' : secret_id,
'Timestamp' : int(time.time()), # int(time.time())
'Version': '2019-03-05'
}
s = get_string_to_sign("POST", endpoint, data)
data["Signature"] = sign_str(secret_key, s, hashlib.sha1)
print(data["Signature"])
# 打印图片转换为base64编码后的字符串信息
print(image_to_string('simple'+os.sep+"dalai.jpg"))
resp = requests.post("https://" + endpoint, data=data)

print(resp.url)
print(resp.text)