如何在不每次都通过浏览器获取新的身份验证代码的情况下使用Python Google API?

spr*_*aff 6 google-api

我正在使用Google API。我以此为起点,这里是实际的Python代码。

我已经在https://console.developers.google.com/apis/credentials创建了OAuth 2.0客户端ID,并client_secret.json按照以下代码中的方式下载了它:

CLIENT_SECRETS_FILE = "client_secret.json"

def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
Run Code Online (Sandbox Code Playgroud)

内容client_secret.json如下:

{
  "installed": {
    "client_id": "**REDACTED**",
    "project_id": "api-project-1014650230452",
    "auth_uri": "https:\/\/accounts.google.com\/o\/oauth2\/auth",
    "token_uri": "https:\/\/accounts.google.com\/o\/oauth2\/token",
    "auth_provider_x509_cert_url": "https:\/\/www.googleapis.com\/oauth2\/v1\/certs",
    "client_secret": "**REDACTED**",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob",
      "http:\/\/localhost"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

整个程序可以正常工作并成功返回有意义的数据集,但是,每次运行该程序时,都会提示我如下:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=...
Enter the authorization code:
Run Code Online (Sandbox Code Playgroud)

我输入了代码,程序运行了,但是每次程序运行时,我都必须访问此URL并获取新的代码。我给人的印象client_secret.json恰恰是为了防止这种情况的发生。

如何使我的CLI Python程序使用API​​,而不必每次都获得一个新的令牌?

Tan*_*ike 5

您想运行脚本而不每次都获取代码。如果我的理解是正确的,那么该修改如何?在此修改中,首次运行脚本时,刷新令牌将保存到文件“ credential_sample.json”。这样,在下一次运行中,您可以使用由刷新令牌检索到的访问令牌使用API​​。因此,您不必每次都检索代码。

修改后的脚本:

请进行如下修改。

来自:
def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_console()
    return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
Run Code Online (Sandbox Code Playgroud) 至 :
from oauth2client import client # Added
from oauth2client import tools # Added
from oauth2client.file import Storage # Added

def get_authenticated_service(): # Modified
    credential_path = os.path.join('./', 'credential_sample.json')
    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, SCOPES)
        credentials = tools.run_flow(flow, store)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Run Code Online (Sandbox Code Playgroud)

注意 :

  • 首次运行时,浏览器将自动打开。在授权范围时,脚本会自动检索代码并为“ credential_sample.json”创建标记。
  • 此修改假定您的当前脚本可以正常工作,只是每次都需要检索代码。

参考文献:

如果这不是您想要的,对不起。