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

相关文章

python模块之subprocess模块级方法的使用

subprocess.run() 运行并等待args参数指定的指令完成,返回CompletedProcess实例。 参数:(*popenargs, input=None, captur...

利用pandas合并多个excel的方法示例

利用pandas合并多个excel的方法示例

具体方法: 1使用panda read_excel 方法加载excel 2使用concat将DataFrame列表进行拼接 3然后使用pd.ExcelWriter对象和to_excel将...

Python cookbook(数据结构与算法)对切片命名清除索引的方法

本文实例讲述了Python对切片命名清除索引的方法。分享给大家供大家参考,具体如下: 问题:如何清理掉到处都是硬编码的切片索引 解决方案:对切片命名 假设有一些代码用来从字符串的固定位置...

彻底搞懂Python字符编码

彻底搞懂Python字符编码

不论你是有着多年经验的 Python 老司机还是刚入门 Python 不久,你一定遇到过UnicodeEncodeError、UnicodeDecodeError 错误,每当遇到错误我们...

Django数据库类库MySQLdb使用详解

Django项目要操作数据库,首先要和数据库建立连接,才能让程序中的数据和数据库关联起来进行数据的增删改查操作 Django项目默认使用mysqldb模块进行和mysql数据库之间的交互...