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的Urllib库的基本使用教程

Python的Urllib库的基本使用教程

1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,...

Python实现字符串与数组相互转换功能示例

Python实现字符串与数组相互转换功能示例

本文实例讲述了Python实现字符串与数组相互转换功能。分享给大家供大家参考,具体如下: 字符串转数组 str = '1,2,3' arr = str.split(',') prin...

Python排序搜索基本算法之选择排序实例分析

Python排序搜索基本算法之选择排序实例分析

本文实例讲述了Python排序搜索基本算法之选择排序。分享给大家供大家参考,具体如下: 选择排序就是第n次把序列中最小的元素排在第n的位置上,一旦排好就是该元素的绝对位置。代码如下:...

Python绘制并保存指定大小图像的方法

绘制直线,三角形,正方形 import matplotlib.pyplot as plt def plotLine(): x = [1,2,3,4,5] y = [3,3,3,3...

在Python中编写数据库模块的教程

在一个Web App中,所有数据,包括用户信息、发布的日志、评论等,都存储在数据库中。在awesome-python-app中,我们选择MySQL作为数据库。 Web App里面有很多地...