python tornado微信开发入门代码

yipeiwu_com6年前Python基础

本文实例为大家分享了python tornado微信开发的具体代码,供大家参考,具体内容如下

#微信入门代码
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.web
import hashlib
import xml.etree.ElementTree as ET
import time

def check_signature(signature, timestamp, nonce):
  # 微信公众平台里输入的token
  token="linden"
  #字典序排序
  list = [token,timestamp,nonce]
  list.sort()
  sha1=hashlib.sha1()
  map(sha1.update,list)
  hashcode=sha1.hexdigest()
  return hashcode == signature

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    signature = self.get_argument('signature')
    timestamp = self.get_argument('timestamp')
    nonce = self.get_argument('nonce')
    echostr = self.get_argument('echostr')
    if check_signature(signature, timestamp, nonce):
      self.write(echostr)
    else:
      self.write('fail')
  def post(self): 
    body = self.request.body
    data = ET.fromstring(body)
    toUser = data.find('ToUserName').text
    fromUser = data.find('FromUserName').text
    createTime = int(time.time())
    msgType = data.find('MsgType').text
    content = data.find('Content').text
    msgId= data.find("MsgId").text
    # from与to在返回的时候要交换
    textTpl = """<xml>
      <ToUserName><![CDATA[%s]]></ToUserName>
      <FromUserName><![CDATA[%s]]></FromUserName>
      <CreateTime>%s</CreateTime>
      <MsgType><![CDATA[%s]]></MsgType>
      <Content><![CDATA[%s]]></Content>
      <MsgId>%s</MsgId>
      </xml>"""
    out = textTpl % (fromUser, toUser, createTime, msgType, content, msgId)
    self.write(out)

application = tornado.web.Application([
  (r"/", MainHandler),
])

if __name__ == "__main__":
  application.listen(80)
  tornado.ioloop.IOLoop.instance().start()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python技能之数据导出excel的实例代码

python技能之数据导出excel的实例代码

本文介绍了python技能之导出excel的实例代码,正好能用到,写出来分享给大家 作为一个数据分析师,下面的需求是经常会遇到的。 从数据库或者现有的文本文件中提取符合要求的数据,做...

一步步解析Python斗牛游戏的概率

过年回家,都会约上亲朋好友聚聚会,会上经常会打麻将,斗地主,斗牛。在这些游戏中,斗牛是最受欢迎的,因为可以很多人一起玩,而且没有技术含量,都是看运气(专业术语是概率)。 斗牛的玩法是:...

numpy 返回函数的上三角矩阵实例

numpy 返回函数的上三角矩阵 np.triu() matrix2=np.triu(matrix1) numpy.triu(m, k=0)[source] Upper tri...

python+influxdb+shell编写区域网络状况表

python+influxdb+shell编写区域网络状况表

本文为大家分享了python+influxdb+shell写一个区域网络状况表,供大家参考,具体内容如下 shell脚本部分: ex:就是ping 各个目的ip10个包,然后获取丢包率...

python flask搭建web应用教程

python flask搭建web应用教程

python flask搭建web应用教程 1.flask介绍 2.所需工具和环境 3.搭建flaskApp 4.具体程序编写 5.综上 1.flask介绍 flask是一款十分轻量级的...