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

相关文章

对Django 中request.get和request.post的区别详解

Django 中request.get和request.post的区别 POST和GET差异: POST和GET是HTTP协议定义的与服务器交互的方法。GET一般用于获取/查询资源信息,...

numpy.ndarray 实现对特定行或列取值

numpy.ndarray 实现对特定行或列取值

如下所示: import numpy as np b = [[1,2,0], [4,5,0], [7,8,1], [4,0,1], [7,11,1] ] a=np.array...

Python制作钉钉加密/解密工具

又是很久没有写技术博客了,盖因最近都在学习知识,也没有总结出什么值得分享的内容,所以一直停笔至今。最近的工作和钉钉的开发打上了交到,官方并没有提供任何Python的SDK,于是只能全部自...

python打包成so文件过程解析

这篇文章主要介绍了python打包成so文件过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 wget https://bo...

Python写的服务监控程序实例

前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4。 到python网站下载源代码,解压到Redhat上,然后运行下面的命令:...