Add support for customizable service url

This commit is contained in:
SuHun Han 2017-03-11 22:31:57 +09:00 committed by ssut
parent 92ea3cd2c1
commit 0f943b6a64
4 changed files with 41 additions and 4 deletions

View File

@ -22,6 +22,7 @@ Features
translate.google.com uses translate.google.com uses
- Auto language detection - Auto language detection
- Bulk translations - Bulk translations
- Customizable service URL
- Connection pooling (the advantage of using requests.Session) - Connection pooling (the advantage of using requests.Session)
- HTTP/2 support - HTTP/2 support
@ -32,7 +33,6 @@ more features are coming soon.
- Proxy support - Proxy support
- Internal session management (for better bulk translations) - Internal session management (for better bulk translations)
- Customizable service URL (translate.google.**com**)
HTTP/2 support HTTP/2 support
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
@ -89,6 +89,20 @@ source language.
>>> translator.translate('veritas lux mea', src='la') >>> translator.translate('veritas lux mea', src='la')
# <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light> # <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light>
Customize service URL
~~~~~~~~~~~~~~~~~~~~~
You can use another google translate domain for translation. If multiple
URLs are provided it then randomly chooses a domain.
.. code:: python
>>> from googletrans import Translator
>>> translator = Translator(service_urls=[
'translate.google.com',
'translate.google.co.kr',
])
Advanced Usage (Bulk) Advanced Usage (Bulk)
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~

View File

@ -5,6 +5,7 @@ A Translation module.
You can translate text using this module. You can translate text using this module.
""" """
import requests import requests
import random
from googletrans import urls, utils from googletrans import urls, utils
from googletrans.compat import PY3 from googletrans.compat import PY3
@ -18,12 +19,13 @@ EXCLUDES = ('en', 'ca', 'fr')
class Translator(object): class Translator(object):
def __init__(self, user_agent=DEFAULT_USER_AGENT): def __init__(self, service_urls=None, user_agent=DEFAULT_USER_AGENT):
self.session = requests.Session() self.session = requests.Session()
self.session.headers.update({ self.session.headers.update({
'User-Agent': user_agent, 'User-Agent': user_agent,
}) })
self.token_acquirer = TokenAcquirer(session=self.session) self.token_acquirer = TokenAcquirer(session=self.session)
self.service_urls = service_urls or ['translate.google.com']
# Use HTTP2 Adapter if hyper is installed # Use HTTP2 Adapter if hyper is installed
try: # pragma: nocover try: # pragma: nocover
@ -32,6 +34,11 @@ class Translator(object):
except ImportError: # pragma: nocover except ImportError: # pragma: nocover
pass pass
def _pick_service_url(self):
if len(self.service_urls) == 1:
return self.service_urls[0]
return random.choice(self.service_urls)
def _translate(self, text, dest='en', src='auto'): def _translate(self, text, dest='en', src='auto'):
if src != 'auto': if src != 'auto':
if src not in LANGUAGES.keys() and src in SPECIAL_CASES.keys(): if src not in LANGUAGES.keys() and src in SPECIAL_CASES.keys():
@ -51,7 +58,8 @@ class Translator(object):
token = self.token_acquirer.do(text) token = self.token_acquirer.do(text)
params = utils.build_params(query=text, src=src, dest=dest, params = utils.build_params(query=text, src=src, dest=dest,
token=token) token=token)
r = self.session.get(urls.TRANSLATE, params=params) url = urls.TRANSLATE.format(host=self._pick_service_url())
r = self.session.get(url, params=params)
data = utils.format_json(r.text) data = utils.format_json(r.text)
return data return data

View File

@ -3,4 +3,4 @@
Predefined URLs used to make google translate requests. Predefined URLs used to make google translate requests.
""" """
BASE = 'https://translate.google.com' BASE = 'https://translate.google.com'
TRANSLATE = 'https://translate.google.com/translate_a/single' TRANSLATE = 'https://{host}/translate_a/single'

View File

@ -1,6 +1,21 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from pytest import raises from pytest import raises
from googletrans import Translator
def test_bind_multiple_service_urls():
service_urls = [
'translate.google.com',
'translate.google.co.kr',
]
translator = Translator(service_urls=service_urls)
assert translator.service_urls == service_urls
assert translator.translate('test', dest='ko')
assert translator.detect('Hello')
def test_latin_to_english(translator): def test_latin_to_english(translator):
result = translator.translate('veritas lux mea', src='la', dest='en') result = translator.translate('veritas lux mea', src='la', dest='en')