Skip to content

Commit

Permalink
Implement translate API v1.4
Browse files Browse the repository at this point in the history
  • Loading branch information
suminb committed Apr 29, 2018
1 parent 9b9b37c commit 2f332cb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions translator/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import re
import sys
import urllib
from urllib.parse import quote_plus
import uuid

import requests
Expand Down Expand Up @@ -498,6 +499,31 @@ def translate_v1_3():
return resp_text, resp_status_code


@api_module.route('/api/v1.4/translate', methods=['get', 'post'])
def translate_v1_4():
request_params = request.form if request.method == 'POST' else request.args
text, source, target = \
[request_params[k] for k in ('text', 'source', 'target')]

url = 'https://www.google.co.kr/async/translate?yv=3'
headers = {
'User-Agent': DEFAULT_USER_AGENT,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Accept': '*/*',
'Referer': 'https://www.google.co.kr/',
'Authority': 'www.google.co.kr',
'Cookie': 'NID=129=; 1P_JAR=2018-04-29-15',
}
data = 'async=translate,sl:{source},tl:{target},st:{text},id:{id}' \
',qc:true,ac:false,_id:tw-async-translate,_pms:s,_fmt:pc'.format(
source=source, target=target, text=quote_plus(text), id=1)
resp = requests.post(url, headers=headers, data=data)

_, _, _, result = resp.text.split('\n')

return result, resp.status_code


@api_module.route('/api/v1.3/exception')
def exception():
raise Exception(request.args.get('message', 'Anything you can imagine'))
4 changes: 2 additions & 2 deletions translator/static/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ var examples = {
};

// URL encoded length, exclusively less than
var LONG_TRANSLATION_THRESHOLD = 1200;
var LONG_TRANSLATION_THRESHOLD = 5000;

var TAGS_TO_REPLACE = {
'&': '&',
Expand Down Expand Up @@ -470,7 +470,7 @@ function sendTranslationRequest(source, target, text, onSuccess, onAlways) {
var requestMethod = textLength < 550 ?
"GET" : "POST";

var url = '/api/v1.3/translate';
var url = '/api/v1.4/translate';

if (msie()) {
sendXDomainRequest(url, requestMethod, {q: text}, onSuccess, onAlways);
Expand Down

0 comments on commit 2f332cb

Please sign in to comment.