# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport jsonimport requestsfrom urlparse import urlparse# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'# apigw access addressUrl = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'HTTPMethod = 'GET' # methodAccept = 'application/json'ContentType = 'application/json'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'# Splice query parameters. The query parameters need to be sorted in lexicographical order.if urlInfo.query :queryStr = urlInfo.querysplitStr = queryStr.split('&')splitStr = sorted(splitStr)sortStr = '&'.join(splitStr)Path = Path + '?' + sortStrContentMD5 = ''GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'xDate = datetime.datetime.utcnow().strftime(GMT_FORMAT)# Modify body contentif HTTPMethod == 'POST' :body = { "arg1": "a", "arg2": "b" }body_json = json.dumps(body)ContentMD5 = base64.b64encode(hashlib.md5(body_json).hexdigest())# Obtain the signature stringsigning_str = 'x-date: %s\\n%s\\n%s\\n%s\\n%s\\n%s' % (xDate, HTTPMethod, Accept, ContentType, ContentMD5, Path)# Compute the signaturesign = 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 + "\\""# Send the requestheaders = {'Host': Host,'Accept': Accept,'Content-Type': ContentType,'x-date': xDate,'Authorization': sign}if(HTTPMethod == 'GET'):ret = requests.get(Url, headers=headers)if(HTTPMethod == 'POST'):ret = requests.post(Url, headers=headers, data=body_json)print(ret.headers)print(ret.text)
# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport jsonimport requestsimport urllibfrom urlparse import urlparse# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'# apigw access addressUrl = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'HTTPMethod = 'POST' # methodAccept = 'application/json'ContentType = 'application/x-www-form-urlencoded'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'ContentMD5 = ''GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'xDate = datetime.datetime.utcnow().strftime(GMT_FORMAT)# Modify body contentbody = { "arg1": "a", "arg2": "b" }argBody = urllib.urlencode(body)# When signing, the form parameters are spliced with the query parameters. The parameters need to be sorted in lexicographical order.if urlInfo.query :argBody = argBody + '&' + urlInfo.querysplitStr = argBody.split('&')argBody = sorted(splitStr)sortStr = '&'.join(argBody)Path = Path + '?' + sortStr# Obtain the signature stringsigning_str = 'x-date: %s\\n%s\\n%s\\n%s\\n%s\\n%s' % (xDate, HTTPMethod, Accept, ContentType, ContentMD5, Path)# Compute the signaturesign = 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 + "\\""# Send the requestheaders = {'Host': Host,'Accept': Accept,'Content-Type': ContentType,'x-date': xDate,'Authorization': sign}if(HTTPMethod == 'GET'):ret = requests.get(Url, headers=headers)if(HTTPMethod == 'POST'):ret = requests.post(Url, headers=headers, data=body)print(ret.headers)print(ret.text)
#! /usr/bin/env python# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport httplib, mimetypesfrom urlparse import urlparse# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'Url = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'# Set form parameters# fields is a sequence of (name, value) elements for regular form fields.# files is a sequence of (name, filename, value) elements for data to be uploaded as files#Example:#Fields = [("arg1", "a"), ("arg2", "b")]#Files = [("file", "@test.txt", open("test.txt", "r").read())]Fields = []Files = []HTTPMethod = 'POST'Accept = 'application/json'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'# Splice query parameters. The query parameters need to be sorted in lexicographical order.if urlInfo.query :queryStr = urlInfo.querysplitStr = queryStr.split('&')splitStr = sorted(splitStr)sortStr = '&'.join(splitStr)Path = Path + '?' + sortStrGMT_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())# Obtain the signature stringsigning_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 outputdef 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' % BOUNDARYreturn content_type, bodydef get_content_type(filename):return mimetypes.guess_type(filename)[0] or 'application/octet-stream'output = post_multipart(Host, Path, Fields, Files)print(output)
# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport jsonimport requestsfrom urllib.parse import urlparsefrom urllib.parse import urlencode# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'# apigw access addressUrl = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'HTTPMethod = 'POST' # methodAccept = 'application/json'ContentType = 'application/x-www-form-urlencoded'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'ContentMD5 = ''GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'xDate = datetime.datetime.utcnow().strftime(GMT_FORMAT)# Modify body contentbody = { "arg1": "a", "arg2": "b" }argBody = urlencode(body)# When signing, the form parameters are spliced with the query parameters. The parameters need to be sorted in lexicographical order.if urlInfo.query :argBody = argBody + '&' + urlInfo.querysplitStr = argBody.split('&')argBody = sorted(splitStr)sortStr = '&'.join(argBody)Path = Path + '?' + sortStr# Obtain the signature stringsigning_str = 'x-date: %s\\n%s\\n%s\\n%s\\n%s\\n%s' % (xDate, HTTPMethod, Accept, ContentType, ContentMD5, Path)# Compute the signaturesign = hmac.new(ApiAppSecret.encode(), msg=signing_str.encode(), digestmod=hashlib.sha1).digest()sign = base64.b64encode(sign).decode()auth = "hmac id=\\"" + ApiAppKey + "\\", algorithm=\\"hmac-sha1\\", headers=\\"x-date\\", signature=\\""sign = auth + sign + "\\""# Send the requestheaders = {'Host': Host,'Accept': Accept,'Content-Type': ContentType,'x-date': xDate,'Authorization': sign}if HTTPMethod == 'GET' :ret = requests.get(Url, headers=headers)if HTTPMethod == 'POST' :ret = requests.post(Url, headers=headers, data=body)print(ret.headers)print(ret.text)
# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport jsonimport requestsfrom urllib.parse import urlparse# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'# apigw access addressUrl = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'HTTPMethod = 'GET' # methodAccept = 'application/json'ContentType = 'application/json'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'# Splice query parameters. The query parameters need to be sorted in lexicographical order.if urlInfo.query :queryStr = urlInfo.querysplitStr = queryStr.split('&')splitStr = sorted(splitStr)sortStr = '&'.join(splitStr)Path = Path + '?' + sortStrContentMD5 = ''GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'xDate = datetime.datetime.utcnow().strftime(GMT_FORMAT)# Modify body contentif HTTPMethod == 'POST' :body = { "arg1": "a", "arg2": "b" }body_json = json.dumps(body)body_md5 = hashlib.md5(body_json.encode()).hexdigest()ContentMD5 = base64.b64encode(body_md5.encode()).decode()# Obtain the signature stringsigning_str = 'x-date: %s\\n%s\\n%s\\n%s\\n%s\\n%s' % (xDate, HTTPMethod, Accept, ContentType, ContentMD5, Path)# Compute the signaturesign = hmac.new(ApiAppSecret.encode(), msg=signing_str.encode(), digestmod=hashlib.sha1).digest()sign = base64.b64encode(sign).decode()auth = "hmac id=\\"" + ApiAppKey + "\\", algorithm=\\"hmac-sha1\\", headers=\\"x-date\\", signature=\\""sign = auth + sign + "\\""# Send the requestheaders = {'Host': Host,'Accept': Accept,'Content-Type': ContentType,'x-date': xDate,'Authorization': sign}if HTTPMethod == 'GET' :ret = requests.get(Url, headers=headers)if HTTPMethod == 'POST' :ret = requests.post(Url, headers=headers, data=body_json)print(ret.headers)print(ret.text)
#! /usr/bin/env python# -*- coding: utf-8 -*-import base64import datetimeimport hashlibimport hmacimport http.client as httplibimport mimetypesfrom urllib.parse import urlparse# Application's `ApiAppKey`ApiAppKey = 'Your ApiAppKey'# Application's `ApiAppSecret`ApiAppSecret = 'Your ApiAppSecret'Url = 'http://service-xxx-xxx.gz.apigw.tencentcs.com/'# Set form parameters# fields is a sequence of (name, value) elements for regular form fields.# files is a sequence of (name, filename, value) elements for data to be uploaded as files#Example:#Fields = [("arg1", "a"), ("arg2", "b")]#Files = [("file", "@test.txt", open("test.txt", "r").read())]Fields = []Files = []HTTPMethod = 'POST'Accept = 'application/json'urlInfo = urlparse(Url)Host = urlInfo.hostnamePath = urlInfo.path# Environment information is not included in the signature pathif Path.startswith(('/release', '/test', '/prepub')) :Path = '/' + Path[1:].split('/',1)[1]Path = Path if Path else '/'# Splice query parameters. The query parameters need to be sorted in lexicographical order.if urlInfo.query :queryStr = urlInfo.querysplitStr = queryStr.split('&')splitStr = sorted(splitStr)sortStr = '&'.join(splitStr)Path = Path + '?' + sortStrGMT_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)body_md5 = hashlib.md5(body.encode()).hexdigest()ContentMD5 = base64.b64encode(body_md5.encode()).decode()#ContentMD5 = base64.b64encode((hashlib.md5(body.encode).hexdigest()).encode).decode()# Obtain the signature stringsigning_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.encode(), msg=signing_str.encode(), digestmod=hashlib.sha1).digest()sign = base64.b64encode(sign).decode()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.encode())response = h.getresponse()output = response.read().decode()return outputdef 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' % BOUNDARYreturn content_type, bodydef get_content_type(filename):return mimetypes.guess_type(filename)[0] or 'application/octet-stream'output = post_multipart(Host, Path, Fields, Files)print(output)
Was this page helpful?