小白求大佬指教
pxn626 发布于2020-11 浏览:1230 回复:1
1
收藏
快速回复
最后编辑于2020-11

# encoding:utf-8
import requests
import json
import time


def gettoken():
AK = "D"
SK = "c"
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK
#【官网获取的AK】&client_secret=【官网获取的SK】'
response = requests.get(host)
if response:
tojson = response.json()
else:
tojson = "获取token出错"
if "出错" in tojson:
print(tojson)
exit(0)
else:
token = tojson["refresh_token"]
timey = tojson["expires_in"] + time.time()
#times = tojson["expires_in"]
cctojson = {}
cctojson["token"] = token
cctojson["timey"] = timey
strtojson = json.dumps(cctojson)
with open("to.txt", "w", encoding="utf-8") as f:
f.write(strtojson)
return token

def scwb(token, text):
headers = {'content-type':'application/x-www-form-urlencoded'}
params = {'access_token':token}
data = {'strategyId':1148, 'text':text}
url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + token
# url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined"
# headers['content-type'] = 'application/x-www-form-urlencoded'
# #text = "不要侮辱伟大的乐侃"
# params['access_token'] = token
# data['text'] = text
r = requests.post(url, data=data, headers=headers)
# r = requests.post(url, data=data, params=params, headers=headers)
print(r.text)

def scwba(token, text):
headers = {'content-type':'application/x-www-form-urlencoded'}
params = {'access_token':token}
data = {"text": "苹果是一家伟大的公司"}
url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + token
# url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined"
# headers['content-type'] = 'application/x-www-form-urlencoded'
# #text = "不要侮辱伟大的乐侃"
# params['access_token'] = token
# data['text'] = text
r = requests.get(url,data)
# r = requests.post(url, data=data, params=params, headers=headers)
if r:
print(r.text)

with open("to.txt", "r", encoding="utf-8") as f:
#print(f.read())
text = f.read()
if "token" not in text:
token = gettoken()
else:
tojson = json.loads(text)
token = tojson["token"]
times = tojson["timey"]
if time.time()>times:
token = gettoken()
print(token)
text = "不要侮辱伟dsf双方的瑟夫和大的乐侃"
scwba(token, text)

 

刚获得token 为什么一用就失效??

收藏
点赞
1
个赞
共1条回复 最后由pxn626编辑于2020-11
#2pxn626回复于2020-11

已解决  token 取错了

0
TOP
切换版块