用django做微信开发

调用了图灵机器人的接口,但微信开发出现了问题,后台用的django,但response怎么也返回不到微信客户端,又不知道该怎么debug。在这里贴出urls.py和views.py,希望有高人可以帮我找找茬。

urls.py

from django.conf.urls import patterns, include, url
from littesnail.views import handleRequest

urlpatterns = patterns(‘‘,
    # Examples:
    url(r^$, handleRequest),
)

views.py:

# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str, smart_unicode
import xml.etree.ElementTree as ET
import urllib,urllib2,time,hashlib
import sys
import json

TOKEN = "12**56"
API_KEY = bc192acc7*****c19342f5f0274

@csrf_exempt
def handleRequest(request):
    if request.method == GET:
        response = HttpResponse(checkSignature(request),content_type="text/plain")
        return response
    elif request.method == POST:
        response = HttpResponse(responseMsg(request),content_type="application/xml")
        return response
    else:
        return None

def checkSignature(request):
    global TOKEN
    signature = request.GET.get("signature", None)
    timestamp = request.GET.get("timestamp", None)
    nonce = request.GET.get("nonce", None)
    echoStr = request.GET.get("echostr",None)

    token = TOKEN
    tmpList = [token,timestamp,nonce]
    tmpList.sort()
    tmpstr = "%s%s%s" % tuple(tmpList)
    tmpstr = hashlib.sha1(tmpstr).hexdigest()
    if tmpstr == signature:
        return echoStr
    else:
        return None

def responseMsg(request):
    #解析微信客户端传来的XML的Post信息
    rawStr = smart_str(request.request.body)
    msg = paraseMsgXml(ET.fromstring(rawStr))
    queryStr = msg.get(Content,You have input nothing~)
    raw_TULINURL = "http://www.tuling123.com/openapi/api?key=%s&info=" % API_KEY
    TULINURL = "%s%s" % (raw_TULINURL,urllib2.quote(queryStr))
    req = urllib2.Request(url=TULINURL)
    result = urllib2.urlopen(req).read()
    hjson=json.loads(result)
    length=len(hjson.keys())
    content=hjson[text]
    if length==3:
        replyContent= robots: +content+hjson[url]
    elif length==2:
        replyContent= robots: +content
    else:
        return "please input again."
    return getReplyXml(msg,replyContent)

def paraseMsgXml(rootElem):
    msg = {}
    if rootElem.tag == xml:
        for child in rootElem:
            msg[child.tag] = smart_str(child.text)
        return msg

def getReplyXml(msg,replyContent):
    extTpl = ‘‘‘<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>‘‘‘;
    extTpl = extTpl % (msg[FromUserName],msg[ToUserName],str(int(time.time())),text,replyContent)
    return extTpl

 

用django做微信开发

上一篇:Java程序运行机制


下一篇:微信成为HTML5技术流行的最大推手