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

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

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

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

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


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


]


关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看