aws lambda踩坑--企业微信中文显示问题

注意:此文只对本次测试有效,并非完全解决方案
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))

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值