首页 > 解决方案 > 使用 Python 存储 Google Auth 凭据

问题描述

我从 Google API 文档中获取了相同的代码。我抓取的代码提示用户授权我的应用程序可以使用他们的帐户来点赞视频。这是代码

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.videos().rate(
        id="eyRGEv3XAxk",
        rating="like"
    )
    request.execute()

if __name__ == "__main__":
    main()

此代码适用于有效的“客户端机密文件”。但是有什么办法让我保存凭据,这样我就不必总是提示用户授权我的应用程序?假设我想在我的代码的另一部分喜欢另一个视频,但我不想再次授权。

标签: pythonapiyoutube

解决方案


使用 python pickle 库来保存和加载凭证对象。


推荐阅读