码迷,mamicode.com
首页 > 微信 > 详细

python+django+新浪sae+有道API实现微信服务号自动翻译

时间:2015-09-23 17:27:39      阅读:445      评论:0      收藏:0      [点我收藏+]

标签:

先看效果:你可以自己用微信搜下"黛莱美北京总代理"找下这个公众。

技术分享

公众号是在淘宝上买的,最偏的那种,无法改名字了,自己玩,就这样了。

直接贴截图,代码,欢迎评论:

技术分享


index.wsgi文件内容:

import sae

from fanyi_project import wsgi

application = sae.create_wsgi_app(wsgi.application)


config.yaml文件内容:

name: fanyi7lk

version: 2


libraries:

- name: "django"

  version: "1.8"


wsgi.py内容:

"""

WSGI config for fanyi_project project.


It exposes the WSGI callable as a module-level variable named ``application``.


For more information on this file, see

https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/

"""


import os

import sys

root = os.path.dirname(__file__)

sys.path.insert(0, os.path.join(root, ‘..‘, ‘fanyi-env/lib/python2.7/site-packages‘))


from django.core.wsgi import get_wsgi_application


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fanyi_project.settings")


application = get_wsgi_application()



views.py内容:

#-*-coding:utf-8-*-

import sys

reload(sys)

sys.setdefaultencoding(‘utf-8‘)

from django.shortcuts import render

from django.http import HttpResponse

from django.views.decorators.csrf import csrf_exempt

import xml.etree.ElementTree as ET


# Create your views here.


import urllib2

import json

import hashlib

import time


TOKEN=‘fuhan‘

MY_ID=‘wx432c635fdcecb85a‘





def xlm_dict(request):

    if request.method == ‘POST‘:

        xml = request.body

        xml_dict =dict((child.tag, child.text) for child in ET.fromstring(xml))

        return xml_dict





def checkSignature(signature, timestamp, nonce):

    tmp = [TOKEN, timestamp, nonce]

    print(tmp)

    tmp.sort()

    code = hashlib.sha1("".join(tmp)).hexdigest()

    result = (code == signature)

    print(result)

    return result



def Mes_receive(xml_dict):

    my_time = int(time.time())

    print(xml_dict)

    cont = xml_dict[‘Content‘]

    print(cont)

    word_fanyi = youdao(cont)

    xml_dict[‘CreateTime‘] = my_time

    xml_dict[‘Content‘] = word_fanyi

    print(xml_dict)

    data = """\

    <xml>

    <ToUserName><![CDATA[%(FromUserName)s]]></ToUserName>

    <FromUserName><![CDATA[%(ToUserName)s]]></FromUserName>

    <CreateTime>%(CreateTime)s</CreateTime>

    <MsgType><![CDATA[text]]></MsgType>

    <Content><![CDATA[%(Content)s]]></Content>

    </xml>"""%(xml_dict)

    print(data)

    return data



def youdao(word):

    try:

        tar_word = urllib2.quote(str(word))

    

        base_url = r‘http://fanyi.youdao.com/openapi.do?keyfrom=youdaofanyi888&key=449995512&type=data&doctype=json&version=1.1&q=‘

        url = base_url + tar_word

        print(url)

        resp = urllib2.urlopen(url)

        # print(resp.read().decode())

        fanyi = json.loads(resp.read())

        trans = ‘error‘

        web_list = fanyi.get(‘web‘)

        liju = ‘‘

        for a in web_list:

                #print(a)

                valua_list = a.get(‘value‘)

                value= ‘;‘.join(valua_list)

                liju = liju+ str(a.get(‘key‘))+‘::‘+str(value)+‘\n‘

        if fanyi[‘errorCode‘] == 0:

             trans ="基本翻译:%s\n发音:%s\n基本释义:%s\n近义词:%s\n例句:\n%s"%(fanyi.get(‘translation‘)[0],fanyi.get(‘basic‘)[‘phonetic‘],fanyi.get(‘basic‘)[‘explains‘][0],fanyi.get(‘query‘),liju)

        print(trans)

        return trans

    except:

        return ‘翻译出错,请输入正确的单词‘




def index(request):

    signature = request.GET.get("signature", "")

    timestamp = request.GET.get("timestamp", "")

    nonce = request.GET.get("nonce")

    # if not any([signature, timestamp, nonce]) or not checkSignature(signature, timestamp, nonce):

    #     return HttpResponse("check failed")

    echostr = request.GET.get("echostr")

    if echostr is not None:

        print(‘to check‘)

        check = checkSignature(signature, timestamp, nonce)


        return HttpResponse(request.GET.get("echostr"))

    print(‘after check‘)

    # if request.method == "GET":

    #     return

    if request.method ==‘POST‘:

        xml_dict = xlm_dict(request)

        response = Mes_receive(xml_dict)

        return HttpResponse(response)

    return HttpResponse(request.POST)


暂时写的比较烂,后面会用到wechat-python-sdk模块。




python+django+新浪sae+有道API实现微信服务号自动翻译

标签:

原文地址:http://my.oschina.net/u/2367514/blog/510096

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!