python tornado微信开发入门代码

yipeiwu_com5年前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设计】。

相关文章

pandas数据清洗,排序,索引设置,数据选取方法

此教程适合有pandas基础的童鞋来看,很多知识点会一笔带过,不做详细解释 Pandas数据格式 Series DataFrame:每个column就是一个Series 基础属性shap...

Python中使用__new__实现单例模式并解析

单例模式是一个经典设计模式,简要的说,一个类的单例模式就是它只能被实例化一次,实例变量在第一次实例化时就已经固定。  在Python中常见的单例模式有None,这就是一个很典...

Python版名片管理系统

Python版名片管理系统

本文实例为大家分享了Python版名片管理系统的具体代码,供大家参考,具体内容如下 先建立cards_main的文件 import cards_tools #无限循环,由用户主动决...

python实现二维数组的对角线遍历

python实现二维数组的对角线遍历

本文实例为大家分享了python实现二维数组的对角线遍历,供大家参考,具体内容如下 第一种情况:从左上角出发,右下角结束 要完成的事情,就像下图: 话不多说,直接上Python实现代码...

Python3里的super()和__class__使用介绍

子类里访问父类的同名属性,而又不想直接引用父类的名字,因为说不定什么时候会去修改它,所以数据还是只保留一份的好。其实呢,还有更好的理由不去直接引用父类的名字,参见 Python's su...