python - 无需每次身份验证即可使用 Google Api 的任何方法?

标签 python google-api youtube-api google-oauth google-api-python-client

我尝试在 PC 的自动运行中使用 python 上的 API。但我不能,因为每次程序启动时,它都会询问我授权码。 这是我的代码:

client_secret_file = "client_secret.json"
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)

有什么帮助吗?谢谢

最佳答案

因为您使用的是 YouTube API,所以您不能使用服务帐户,您需要使用 Oauth2。

Oauth2 可以返回一个叫做刷新 token 的东西,如果你存储这个 token ,你的代码就可以在下次运行时访问刷新 token ,并使用刷新 token 请求一个新的访问 token ,这样它就不需要问你了每次运行时都会访问您的数据。

# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

我知道是否包含刷新 token 的唯一官方示例在这里 Python quickstart您将需要为 YouTube 更改它,但实际上您只需要授权代码,只需将其插入您的代码即可,您应该是 GTG

关于python - 无需每次身份验证即可使用 Google Api 的任何方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63837906/

相关文章:

python - django createsuperuser 不工作

google-api - 通过电子表格 API 更新包含大量数据的 Google 电子表格的最快方法是什么?

url - 如何使用 api 以 JSON 格式获取最受欢迎的意大利 youtube channel 列表?

c# - 谷歌通讯录 API

android - 生成 token 以访问谷歌帐户

youtube - 如何在 YouTube 搜索 API 中按时长过滤

youtube-api - YouTube 数据 API (v3) 中弃用 RecordingDetails.location

python - 如何根据python中的Where函数获取两列值

python - 更新指向 settings.AUTH_USER_MODEL 的关系

python - Dash,如何根据点击的按钮进行回调?