问题描述
我在Google API中创建了一个服务帐户来检索拟合数据。
如果我在API游乐场中尝试,它可以正常工作(我可以看到可用的不同数据源)
如果我尝试使用以下代码:
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/fitness.activity.read']
SERVICE_ACCOUNT_FILE = 'api-project-248165331787-5a2b3821f120.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,scopes=SCOPES)
fit = googleapiclient.discovery.build('fitness','v1',credentials=credentials)
response = fit.users().dataSources().list(userId='me').execute()
print(response)
我得到一个空白清单作为回应。我想念什么?
谢谢
解决方法
对于其他正在寻找通过脚本使用python来访问适合数据的方法的人:
转到Google api控制台:https://console.cloud.google.com/apis/credentials?project=\ :
- 单击“创建凭据”-> OAuthClientId->应用程序类型->桌面应用程序
- 下载json凭据
- 运行以下脚本:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes,delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/fitness.activity.read']
def main():
creds = None
# The file token.pickle stores the user's access and refresh tokens,and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle','rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available,let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json',SCOPES)
creds = flow.run_console()
# Save the credentials for the next run
with open('token.pickle','wb') as token:
pickle.dump(creds,token)
fit = build('fitness','v1',credentials=creds)
# Call the Drive v3 API
response = fit.users().dataSources().list(userId='me').execute()
...
if __name__ == '__main__':
main()
脚本会提示一个url,将其放入浏览器中,然后将返回的代码写回脚本输入中。
感谢@DalmTo提供的提示