forked from raspberry-pi-org/voiceAssistant
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetchToken.py
61 lines (52 loc) · 1.69 KB
/
fetchToken.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
59
60
61
import sys
import json
# 打印所有 python 解释器可以搜索到的所有路径
sys.path.append('../')
# print(sys.path)
# 导入自定义包
from config.apiConfig import *
# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.parse import quote_plus
else:
import urllib2
from urllib import quote_plus
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
from urllib import urlencode
# 替换你的 API_KEY
# API_KEY = ''
# # 替换你的 SECRET_KEY
# SECRET_KEY = ''
# TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
def fetch_token():
params = {'grant_type': 'client_credentials',
'client_id': API_KEY,
'client_secret': SECRET_KEY}
post_data = urlencode(params)
if (IS_PY3):
post_data = post_data.encode('utf-8')
req = Request(TOKEN_URL, post_data)
try:
f = urlopen(req, timeout=5)
result_str = f.read()
except URLError as err:
print('token http response http code : ' + str(err.code))
result_str = err.read()
if (IS_PY3):
result_str = result_str.decode()
result = json.loads(result_str)
if ('access_token' in result.keys() and 'scope' in result.keys()):
if not 'audio_tts_post' in result['scope'].split(' '):
print('please ensure has check the tts ability')
return ''
return result['access_token']
else:
print('please overwrite the correct API_KEY and SECRET_KEY')
return ''