python wechat flask_python3+flask不能解析消息

执行:

body = request.data.decode('utf-8')

wechat.parse_data(body,msg_signature=signature,timestamp=timestamp,nonce=nonce)

异常如下:

File "/usr/local/lib/python3.4/site-packages/wechat_sdk/basic.py", line 155, in parse_data

nonce=nonce,

File "/usr/local/lib/python3.4/site-packages/wechat_sdk/lib/crypto/crypto.py", line 112, in decrypt_message

return self._decrypt_message(msg, msg_signature, timestamp, nonce)

File "/usr/local/lib/python3.4/site-packages/wechat_sdk/lib/crypto/crypto.py", line 94, in _decrypt_message

encrypt = msg['Encrypt']

TypeError: byte indices must be integers, not str

因为对pthon2、python3本身不熟悉,看了代码,发现问题在:

if isinstance(msg, six.string_types):

try:

msg = xmltodict.parse(to_text(msg))['xml']

except Exception as e:

raise ParseError(e)

这里的 msg = xmltodict.parse(to_text(msg))['xml']未能执行。

在flask中,直接把request.data返回的是字节组。如果直接把字节组传递给parse函数,以现在sdk的实现上要做几次转换,最后上述错误依然发生。

因为我本身对python了解非常浅,盼解决。

代码如下

from flask import Flask,request,make_response

app = Flask(__name__)

app.debug=True

from wechat_sdk import WechatConf

weconf = WechatConf(

appid='....',

appsecret='....',

encrypt_mode='safe', # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式

token='....',

encoding_aes_key='....' # 如果传入此值则必须保证同时传入 token, appid

)

from wechat_sdk import WechatBasic

wechat = WechatBasic(conf=weconf)

@app.route('/wcs',methods=['GET','POST'])

def wechat_entry():

args = request.args

signature = args.get('signature','')

timestamp = args.get('timestamp','')

nonce = args.get('nonce','')

if request.method == 'GET':

echostr = args.get('echostr','')

if wechat.check_signature(signature, timestamp, nonce):

print ("OK")

return make_response(echostr)

else:

print ("WRONG")

return make_response("")

else:

body = request.data.decode('utf-8')

#如果以下方法调用,依然出现异常

#body = request.data

wechat.parse_data(body,msg_signature=signature,timestamp=timestamp,nonce=nonce)

print (wechat.message)

return make_response("")

if __name__ == '__main__':

app.run(host="0.0.0.0", port=8080, debug=True)

python版本:Python 3.4.2 (Python 3.4.4上也有以上问题)

python包:

beautifulsoup4==4.4.1

bs4==0.0.1

Flask==0.10.1

itsdangerous==0.24

Jinja2==2.8

MarkupSafe==0.23

pycrypto==2.6.1

requests==2.6.0

six==1.10.0

wechat-sdk==0.6.3

Werkzeug==0.10.4

xmltodict==0.9.2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值