Skip to content

Commit

Permalink
增加超时自动重新登录
Browse files Browse the repository at this point in the history
  • Loading branch information
bebound committed Apr 17, 2014
1 parent b770745 commit cb97e34
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -14,7 +14,7 @@ Microsoft(Bing) translate API for python3

----------

###Install
###Installation

pip install mstranslate

Expand Down
8 changes: 6 additions & 2 deletions __init__.py
@@ -1,5 +1,6 @@
import json
import re
import time
import requests


Expand Down Expand Up @@ -35,17 +36,20 @@ def accessToken(self):
raise AuthenticationFailed(result['error_description'])
else:
self.access_token = result['access_token']
self.time = time.time()

def translate(self, text, toLang, fromLang=None):
if not self.access_token:
if (not self.access_token):
self.accessToken()
elif int(time.time() - self.time) > 550:
self.accessToken()
authToken = 'Bearer ' + self.access_token
headers = {'Authorization': authToken}
params = {'text': text, 'from': fromLang, 'to': toLang}
result = requests.get('http://api.microsofttranslator.com/v2/Http.svc/Translate', params=params,
headers=headers)
if 'Argument Exception' in result.text:
error=re.search(r'<p>Message:(.*?)</p>',result.text.replace('\n','')).group(1)
error = re.search(r'<p>Message:(.*?)</p>', result.text.replace('\n', '')).group(1)
raise ArgumentException(error)
else:
return result.text[68:-9]
Expand Down

0 comments on commit cb97e34

Please sign in to comment.