1

我正在学习使用 api,现在我尝试从控制台获取运行 python 脚本的设备列表。已安装 Python 客户端库。

示例.py

import pprint
import sys
from apiclient.discovery import build
import json


api_key = 'AIzaSyBNv8k-zm_TkytbBMJVkR7_wjc'


service = build('androidmanagement', 'v1', developerKey=api_key)


response = service.enterprises().devices().list(parent="enterprises/LC03w9087868").execute()

pprint.pprint(response)

我得到了错误

HttpError 401 when requesting https://androidmanagement.googleapis.com/v1/enterprises/LC03w9087868/devices?key=AIzaSyBNv8k-zm_TkytbBMJVkR7_wjc&alt=json returned "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.">

我需要在代码中添加什么来自动进行身份验证?

4

1 回答 1

3

从提示@tehhowch得出结论后,我找到了解决问题的方法。

相反,ApiKey 需要使用 OAuth2ServiceAccount。此页面上的更多信息。我的任务的示例代码:

import pprint
from apiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/androidmanagement']
SERVICE_ACCOUNT_FILE = '//home/y700/Downloads/Cupla-v3.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)


service = build('androidmanagement', 'v1', credentials=credentials)
response = service.enterprises().devices().list(parent="enterprises/LC0XXXXXX98").execute()

pprint.pprint(response)

SCOPES 参数可以从该文档中单独选择。

于 2019-03-14T08:27:42.327 回答