代码之家  ›  专栏  ›  技术社区  ›  spraff

如何使用python google api而不每次都通过浏览器获取新的认证代码?

  •  4
  • spraff  · 技术社区  · 7 年前

    我在玩谷歌API。我正在使用 this 作为起点, here 是实际的python代码。

    我已在创建了OAuth 2.0客户端ID https://console.developers.google.com/apis/credentials 下载为 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)
    

    的内容 客户机\u 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"
        ]
      }
    }
    

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

    Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=...
    Enter the authorization code:
    

    我输入代码,程序就可以运行了,但是每次程序运行时,我都必须访问这个URL并获得一个新的代码。我觉得 客户机\u secret.json 正是为了防止这种必要性而存在的。

    我该怎么做才能让我的cli python程序使用API而不必每次都获得一个新的令牌呢?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Tanaike    7 年前

    您希望每次运行脚本时都不检索代码。如果我的理解是正确的,这个修改如何?在这个修改中,当脚本第一次运行时,刷新令牌被保存到“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)
    
    到:
    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)
    

    注:

    • 第一次运行时,浏览器将自动打开。当您授权作用域时,脚本会自动检索代码并创建“credential_sample.json”的标记。
    • 这种修改假定当前脚本可以工作,除了每次都需要检索代码。

    参考文献:

    如果这不是你想要的,我很抱歉。