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

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

143913_Py4r_2367514.jpg

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

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

144455_NhKq_2367514.png


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模块。

——————————————————————————————————————————

#-*-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)



def home(request):

    a="""

    <h1>hello</h1>

    <script type="text/javascript" name="baidu-tc-cerfication" data-appid="6981525" src="http://apps.bdimg.com/cloudaapi/lightapp.js"></script>

    """

    return HttpResponse(a)

"""fanyi_project URL Configuration


The `urlpatterns` list routes URLs to views. For more information please see:

    https://docs.djangoproject.com/en/1.8/topics/http/urls/

Examples:

Function views

    1. Add an import:  from my_app import views

    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')

Class-based views

    1. Add an import:  from other_app.views import Home

    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')

Including another URLconf

    1. Add an import:  from blog import urls as blog_urls

    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))

"""

from django.conf.urls import include, url

from django.contrib import admin

from fanyi.views import *


urlpatterns = [

    url(r'^admin/', include(admin.site.urls)),

    url(r'^weixin/$', index, name='index'),

    url(r'^$', home, name='home'),


]


转载于:https://my.oschina.net/u/2367514/blog/510096

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值