使用YouTube API Python代码发布评论时重复触发授权请求的问题求助
Hey there! The reason your code prompts you to authorize every single time is that it doesn’t save your OAuth credentials after the first successful login. Right now, the credentials only exist for that one script session—once the script finishes running, they’re gone, so you have to start over each time.
Let’s fix that by adding credential persistence logic:
Step 1: Understand the Fix
We’ll modify the code to:
- Check for a saved token file (we’ll use
token.json) that stores your authorized credentials - Load credentials from this file if it exists
- If no valid credentials are found, run the authorization flow and save the new credentials to the file for future use
Step 2: Modified Full Code
Here’s the updated script with persistence built in:
# -*- coding: utf-8 -*- # Sample Python code for youtube.commentThreads.insert import os import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request 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 = "post.json" token_file = "token.json" # File to store our persistent credentials credentials = None # Load saved credentials if token.json exists if os.path.exists(token_file): credentials = Credentials.from_authorized_user_file(token_file, scopes) # Handle expired or missing credentials if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: # Auto-refresh expired credentials (no manual auth needed) credentials.refresh(Request()) else: # Run the authorization flow if no valid credentials exist flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console() # Save credentials to token.json for next run with open(token_file, "w") as token: token.write(credentials.to_json()) youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials) request = youtube.commentThreads().insert( part="snippet", body={ "snippet": { "videoId": "VIDEO_ID", "topLevelComment": { "snippet": { "textOriginal": "This is the start of a comment thread." } } } } ) response = request.execute() print(response) if __name__ == "__main__": main()
Key Changes Breakdown
- Token File Management: We added checks for
token.json—this file will be created after your first successful authorization and reused for all future runs. - Auto-Refresh: If your credentials expire, the script will automatically refresh them using the refresh token (no need to go through the full auth flow again).
- Persistence: After every successful auth or refresh, we write the latest credentials back to
token.jsonto ensure they’re saved.
Quick Notes
- You’ll still need to go through the authorization flow once when you first run the updated script. After that, it’ll skip this step entirely.
- Keep
token.jsonsecure—it contains sensitive data that grants access to your YouTube account. Never share it or commit it to version control. - If you ever need to re-authorize (e.g., change scopes or revoke access), just delete
token.jsonand run the script again.
内容的提问来源于stack exchange,提问作者romainlavisse
相关产品推荐
相关产品推荐

