import base64
import datetime
import hashlib
import hmac
import httplib, mimetypes
from urlparse import urlparse
ApiAppKey = 'Your ApiAppKey'
ApiAppSecret = 'Your ApiAppSecret'
Url = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'
Fields = []
Files = []
HTTPMethod = 'POST'
Accept = 'application/json'
urlInfo = urlparse(Url)
Host = urlInfo.hostname
Path = urlInfo.path
if Path.startswith(('/release', '/test', '/prepub')) :
Path = '/' + Path[1:].split('/',1)[1]
Path = Path if Path else '/'
if urlInfo.query :
queryStr = urlInfo.query
splitStr = queryStr.split('&')
splitStr = sorted(splitStr)
sortStr = '&'.join(splitStr)
Path = Path + '?' + sortStr
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
xDate = datetime.datetime.utcnow().strftime(GMT_FORMAT)
def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
ContentMD5 = base64.b64encode(hashlib.md5(body).hexdigest())
signing_str = 'x-date: %s\n%s\n%s\n%s\n%s\n%s' % (
xDate, HTTPMethod, Accept, content_type, ContentMD5, Path)
sign = hmac.new(ApiAppSecret, msg=signing_str, digestmod=hashlib.sha1).digest()
sign = base64.b64encode(sign)
auth = "hmac id=\"" + ApiAppKey + "\", algorithm=\"hmac-sha1\", headers=\"x-date\", signature=\""
sign = auth + sign + "\""
h = httplib.HTTPConnection(host)
h.putrequest(HTTPMethod, selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.putheader('accept', Accept)
h.putheader('x-date', xDate)
h.putheader('Authorization', sign)
h.endheaders()
h.send(body)
response = h.getresponse()
output = response.read()
return output
def encode_multipart_formdata(fields, files):
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in
files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
output = post_multipart(Host, Path, Fields, Files)
print(output)