python+django+新浪sae+有道API實現微信服務號自動翻譯

先看效果:你能夠本身用微信搜下"黛萊美北京總代理"找下這個公衆。
javascript

公衆號是在淘寶上買的,最偏的那種,沒法更名字了,本身玩,就這樣了。java

直接貼截圖,代碼,歡迎評論:python


index.wsgi文件內容:
web

import saedjango

from fanyi_project import wsgijson

application = sae.create_wsgi_app(wsgi.application)api


config.yaml文件內容:微信

name: fanyi7lk網絡

version: 2app


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'),


]

相關文章
相關標籤/搜索