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

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

技术分享

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

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

技术分享

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 ="基本翻译:%sn发音:%sn基本释义:%sn近义词:%sn例句: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

以上是python+django+新浪sae+有道API实现微信服务号自动翻译的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>