python3:调用阿里云小蜜代码示例

网友投稿 302 2022-08-26

python3:调用阿里云小蜜代码示例

最近有一个项目需要调用阿里云小蜜,我就拿python调用了一下,然后在官网居然没有找到很好的sample code。就只能自己硬着头皮写一下啦

import base64import urllib.parseimport hmacfrom hashlib import sha1import requestsimport uuidimport timeimport hmac,sslALIYUN_ACCESS_KEY_ID="your id"ALIYUN_ACCESS_KEY_SECRET="your secret"# 解决 访问ssl网站证书的问题try: _create_unverified_= ssl._create_unverified_contextexcept AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default passelse: # Handle target environment that doesn't support HTTPS verification ssl._create_default_= _create_unverified_= { 'Format':'JSON', 'Version':'2017-10-11', 'SignatureMethod':'HMAC-SHA1' }timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())D['SignatureNonce']=str(uuid.uuid1())D['SignatureVersion']=1.0D['AccessKeyId']=ALIYUN_ACCESS_KEY_IDD['Timestamp']=timestampdef percent_encode(encodeStr): encodeStr = str(encodeStr) res = urllib.parse.quote(encodeStr) res = res.replace('+', '%20') res = res.replace('*', '%2A') res = res.replace('%7E', '~') return resdef sign(parameters): sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0]) print(sortedParameters) canonicalizedQueryString = '' for (k, v) in sortedParameters: canonicalizedQueryString += '&' + percent_encode(k) + '=' + percent_encode(v) stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:]) # 使用get请求方法 bs = ALIYUN_ACCESS_KEY_SECRET + '&' bs = bytes(bs, encoding='utf8') stringToSign = bytes(stringToSign, encoding='utf8') h = hmac.new(bs, stringToSign, sha1) # 进行编码 signature = base64.b64encode(h.digest()).strip() return signatureD['Action']="Chat"D['InstanceId']="your instance id" #你阿里云的机器人实例idD['Utterance']="电脑黑屏了怎么办"D['Signature'] = sign(D)sortedParameters = sorted(D.items(), key=lambda D: D[0])# print(D["Signature"])# print(sortedParameters)url = '+ urllib.parse.urlencode(sortedParameters)print(url)r = requests.get(url)print(r.text)

运行成功了,我的输出为:

{"SessionId":"672d532e9e1e40c09563828f54ee5b05","Messages":[{"Text":{},"Type":"Knowledge","Knowledge":{"Id":"74952","Content":"亲,先确认一下是否是没有接入电源,电量过低导致的黑屏,如果不是请到IT服务台报修,IT管理员会根据检测情况处理哦。","AnswerSource":"KnowledgeBase","Title":"电脑黑屏了怎么办","Summary":"亲,先确认一下是否是没有接入电源,电量过低导致的黑屏,如果不是请到IT服务台报修,IT管理员会根据检测情况处理哦。"}}],"MessageId":"0bb0e211d48d42acaf7f6e1924f7482c","RequestId":"D241002A-FADE-4C86-8180-9CD0B857017E"}

参考文献

[1].会话.https://help.aliyun.com/document_detail/60463.html?spm=a2c4g.11186623.6.555.rdcox6

[3].签名机制.https://help.aliyun.com/document_detail/60762.html?spm=a2c4g.11186623.6.553.lFcX1e

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1073. Adding Two Negabinary Numbers
下一篇:国外服务器上玩游戏延迟很高,什么原因造成的?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~