适用于Android Management API的有效身份验证凭据

时间:2019-03-13 13:56:14

标签: android python google-api google-api-python-client android-management-api

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

sample.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.">

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

1 个答案:

答案 0 :(得分:3)

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

ApiKey则需要使用OAuth2ServiceAccount。有关更多信息,请访问page。我的任务的示例代码:

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)

可以从此document中单独选择SCOPES参数。