python+flask+SAE 微信公共平台开发的小小的demo

来源:互联网 发布:抚仙湖水下古城 知乎 编辑:程序博客网 时间:2024/06/10 06:13

很简单的一个demo,不过在完成之前也走了一些弯路。

SAE开发平台的申请就不说了,很简单,也比较方便。

需要说下的是微信token的验证,平台需要实名认证之后才可以验证成功。

demo代码如下:

# -*- coding:utf-8 -*-                             #中文编码import sysreload(sys)                                        #不加这部分好像处理中文还是会出问题sys.setdefaultencoding('utf-8')import time  from flask import Flask,request, make_response  import hashlib  import xml.etree.ElementTree as ETapp = Flask(__name__)app.debug = True@app.route('/')                                    #网址def index():    return 'Index Page'@app.route('/weixin/', methods = ['GET', 'POST'] ) def wechat_auth():                                 #处理微信请求的处理函数,get方法用于认证,post方法取得微信转发的数据    if request.method == 'GET':        token='liyang'        data = request.args        signature = data.get('signature','')        timestamp = data.get('timestamp','')        nonce = data.get('nonce','')        echostr = data.get('echostr','')        s = [timestamp,nonce,token]        s.sort()        s = ''.join(s)        if (hashlib.sha1(s).hexdigest() == signature):            return make_response(echostr)    else:        rec = request.stream.read()                     #接收消息        xml_rec = ET.fromstring(rec)                    #用xml处理        tou = xml_rec.find('ToUserName').text         fromu = xml_rec.find('FromUserName').text        content = xml_rec.find('Content').text                content = message_del(content)                   #调用处理程序        xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"        response = make_response(xml_rep % (fromu,tou,str(int(time.time())), content))        response.content_type='application/xml'        return responsedef message_del(content):                              #次数是自定义的消息处理函数,自由发挥    if "baidu" in content:                                    message = "www.baidu.com"    elif "金牛" in content:        message = "贪财好色小心眼"    else:        message = "我不知道!"    return messageif __name__ == '__main__':    app.run()


0 0
原创粉丝点击