注意:此文只对本次测试有效,并非完全解决方案
lambda中向企业微信应用发送中文测试消息,收到字符为unicode编码明文
测试模板为
{
"key1": "测试消息"
}
纠正后的代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import json
import requests
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
corpid = 'xxx'
agentid = 'xxx'
appsecret = 'xxx'
toparty = 1
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + \
corpid + '&corpsecret=' + appsecret
def lambda_handler(event, context):
info = str(event['key1'])
print(info)
req = requests.get(token_url)
accesstoken = req.json()['access_token']
msgsend_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken
params = {
"touser": '@all',
"toparty": toparty,
"msgtype": "text",
"agentid": agentid,
"text": {
"content": info
},
"safe": 0
}
req = requests.post(msgsend_url, data=json.dumps(params, ensure_ascii=False))
errcode = json.loads(req.text)['errcode']
if errcode == 0:
print('Succesfully')
else:
print('Failed')
原因为json dump时会对中文进行编码,导致最终发送到企业微信接口的中文消息成为unicode明文,只要声明ensure_ascii=False即可
req = requests.post(msgsend_url, data=json.dumps(params, ensure_ascii=False))
来源:CSDN
作者:大囚长
链接:https://blog.csdn.net/Jailman/article/details/103479512