欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python tornado微信开发入门代码

程序员文章站 2022-04-09 13:49:16
本文实例为大家分享了python tornado微信开发的具体代码,供大家参考,具体内容如下 #微信入门代码 #!/usr/bin/env python2.7...

本文实例为大家分享了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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。