def get_token(self): if os.path.exists(self.token_filepath): token = FileHelper.open_json(self.token_filepath).get(self.name) if time.time() > float(token.get('expires_on')): print('token已过期 重新获取') refresh_token = token.get('refresh_token') discovery_token = self.refresh_token(refresh_token, api_discovery_id) url, urlid = self.get_onedrive_api_urls( discovery_token.get('access_token')) token = self.refresh_token( discovery_token.get('refresh_token'), urlid) if token.get('access_token'): data = FileHelper.open_json(self.token_filepath) data[self.name] = token data[self.name]['api_url'] = url data[self.name]['api_url_id'] = urlid FileHelper.write_json(self.token_filepath, data) return token.get('access_token') else: print('获取失败,没有access_token:') print(token) else: return token.get('access_token')
def auth(self): print( auth_url.format(client_id=self.client_id, redirect_uri=redirect_uri)) print( '请用浏览器打开上面链接,登陆等待跳转后,复制URL地址中code参数的值,注意不要多复制后面的&session_state参数') code = input('请输入code:') auth_param = 'client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={redirect_uri}&resource=https://api.office.com/discovery/' auth_param = auth_param.format(client_id=self.client_id, code=code, client_secret=self.client_secret, redirect_uri=redirect_uri) headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(api_auth_url, data=auth_param, headers=headers) data = json.loads(response.text) access_token = data['access_token'] discovery_token = self.refresh_token(data.get('refresh_token'), api_discovery_id) url, urlid = self.get_onedrive_api_urls( discovery_token.get('access_token')) token = self.refresh_token(discovery_token.get('refresh_token'), urlid) if os.path.exists(self.token_filepath): data = FileHelper.open_json(self.token_filepath) try: data[self.name] = token data[self.name]['api_url'] = url data[self.name]['api_url_id'] = urlid except: token['api_url'] = url token['api_url_id'] = urlid data = {self.name: token} else: token['api_url'] = url token['api_url_id'] = urlid data = {self.name: token} FileHelper.write_json(self.token_filepath, data) #print(data[self.name]) print('保存token完成')
def get_api_url(self): return FileHelper.open_json(self.token_filepath).get( self.name).get('api_url')