使用网络图片
```python
#!/usr/bin/env python
#coding=utf-8
import datetime
import hmac
import hashlib
import json
from urllib.parse import urlparse
import base64
import http.client
# 获取时间
def get_current_date():
date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
return date
# 计算MD5+BASE64
def getcode(bodyData):
temp = bodyData.encode("utf-8")
md5 = hashlib.md5()
md5.update(temp)
md5str = md5.digest() # 16位
b64str = base64.b64encode(md5str)
return b64str
# 计算 HMAC-SHA1
def to_sha1_base64(stringToSign, secret):
hmacsha1 = hmac.new(secret.encode(), stringToSign.encode(), hashlib.sha1)
return base64.b64encode(hmacsha1.digest())
# 初始参数设置
ak_id = '********'
ak_secret = '********'
datetime1 = get_current_date() # 获取时间
# 根据实际测试需要设置自己的图片URL
options = {
'url': 'https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute',
'method': 'POST',
'body': json.dumps({"type": "0", "image_url":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1553926699&di=3e4484731c8897c57e67b3f632801f9a&src=http://b-ssl.duitang.com/uploads/item/201603/28/20160328121906_ErzAB.jpeg"}, separators=(',', ':')),
'headers': {
'accept': 'application/json',
'content-type': 'application/json',
'date': datetime1
}
}
body = '' # 请求body参数
if 'body' in options:
body = options['body']
print(body)
bodymd5 = '' # 计算获取请求body的md5值
if not body == '':
bodymd5 = getcode(body)
bodymd5 = bodymd5.decode(encoding='utf-8')
urlPath = urlparse(options['url'])
restUrl = urlPath[1]
path = urlPath[2]
# 拼接请求签名字符串
stringToSign = options['method'] + '\n' + options['headers']['accept'] + '\n' + bodymd5 + '\n' + options['headers']['content-type'] + '\n' + options['headers']['date'] + '\n' + path
signature = to_sha1_base64(stringToSign, ak_secret)
signature = signature.decode(encoding='utf-8')
authHeader = 'Dataplus ' + ak_id + ':' + signature # 组合认证Authorization
# 请求Header
headers = {
# Request headers
'Content-Type': options['headers']['content-type'],
'Authorization': authHeader,
'Date': datetime1,
'Accept': options['headers']['accept']
}
try:
# 设置http请求参数
conn = http.client.HTTPSConnection(restUrl)
conn.request(options['method'], path, body, headers)
response = conn.getresponse()
data = response.read()
print("Result: ", data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
使用本地图片
```python
#!/usr/bin/env python
#coding=utf-8
import datetime
import hmac
import hashlib
import json
from urllib.parse import urlparse
import base64
import http.client
class AliNetworkManager:
def __init__(self):
self.ak_id = '******'
self.ak_secret = '******'
self.options = {
'url': 'https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute',
'method': 'POST',
'headers': {
'accept': 'application/json',
'content-type': 'application/json',
# 'date': self.get_current_date
}
}
# 获取时间
def get_current_date(self):
date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
return date
# 计算MD5+BASE64
def getcode(self,bodyData):
temp = bodyData.encode("utf-8")
md5 = hashlib.md5()
md5.update(temp)
md5str = md5.digest() # 16位
b64str = base64.b64encode(md5str)
return b64str
# 计算 HMAC-SHA1
def to_sha1_base64(self,stringToSign, secret):
# 1
hmacsha1 = hmac.new(secret.encode(), stringToSign.encode(), hashlib.sha1)
return base64.b64encode(hmacsha1.digest())
def img_content_to_base64(self,jpg_content):
base64_data = base64.b64encode(jpg_content)
return base64_data.decode()
def generate_auth_header(self, bodymd5, path, cur_date):
# 拼接请求签名字符串
stringToSign = self.options['method'] + '\n' + self.options['headers']['accept'] + '\n' + bodymd5 + '\n' + \
self.options['headers']['content-type'] + '\n' + cur_date + '\n' + path
signature = self.to_sha1_base64(stringToSign, self.ak_secret)
signature = signature.decode(encoding='utf-8')
authHeader = 'Dataplus ' + self.ak_id + ':' + signature # 组合认证Authorization
return authHeader
def body_md5sum(self,body):
bodymd5 = self.getcode(body)
return bodymd5.decode(encoding='utf-8')
def url_path(self):
urlPath = urlparse(self.options['url'])
restUrl = urlPath[1]
path = urlPath[2]
return restUrl,path
def body_content_of_jpg_content(self,jpg_content):
return json.dumps({'type': 1, 'content': self.img_content_to_base64(jpg_content)},separators=(',', ':'))
def post_header(self,authHeader,datetime1):
headers = {
# Request headers
'Content-Type': self.options['headers']['content-type'],
'Authorization': authHeader,
'Date': datetime1,
'Accept': self.options['headers']['accept']
}
return headers
def process_jpg_content(self,jpg_content):
body = self.body_content_of_jpg_content(jpg_content)
bodymd5 = self.body_md5sum(body)
datetime1 = self.get_current_date()
restUrl,path = self.url_path()
authHeader = self.generate_auth_header(bodymd5, path, datetime1)
headers = self.post_header(authHeader,datetime1)
try:
# 设置http请求参数
conn = http.client.HTTPSConnection(restUrl)
conn.request(self.options['method'], path, body, headers)
response = conn.getresponse()
data = response.read()
conn.close()
return data
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
if __name__ == '__main__':
aliManager = AliNetworkManager()
# 读取本地图片
filenamePath = "./test/img_423.jpg" # 测试图片存放在项目目录下
base64_data = ''
with open(filenamePath, "rb") as f:
base64_data = f.read()
aliManager.process_jpg_content(base64_data)