-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.py
58 lines (45 loc) · 1.75 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import requests
import json
import os
from dotenv import load_dotenv
# DeepL API auth key stored in .env
load_dotenv()
class Connection():
def __init__(self):
super().__init__()
self.translate
self.request
self.invoke
def translate(self, text, language):
# Arguements for API auth key,
# text for translation and target language
url = 'https://api-free.deepl.com/v2/translate?'
data = {'auth_key': os.environ['AUTH_KEY'],
'text': text,
'target_lang': language}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Post request to API with above arguements
response = requests.post(url, data, headers)
# Convert response to JSON
jsonResponse = response.json()
# Return the translated text
return(jsonResponse["translations"][0]["text"])
@staticmethod
def request(action, **params):
return {'action': action, 'params': params, 'version': 6}
@staticmethod
def invoke(action, **params):
requestJson = json.dumps(
Connection.request(action, **params)
).encode('utf-8')
response = requests.post('http://localhost:8765', requestJson)
jsonResponse = response.json()
if len(jsonResponse) != 2:
raise Exception('response has an unexpected number of fields')
if 'error' not in jsonResponse:
raise Exception('response is missing required error field')
if 'result' not in jsonResponse:
raise Exception('response is missing required result field')
if jsonResponse['error'] is not None:
raise Exception(jsonResponse['error'])
return jsonResponse['result']