0

I am writing a program about the YouTube API

flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
credentials = flow.run_console()
youtube_analytics = googleapiclient.discovery.build("youtubeAnalytics", "v2", credentials=credentials)

Finally it will return a 'Resource' object, can I store this object?

So that I can get this object to use in the future just by referring to the file

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
nike01705
  • 35
  • 4

2 Answers2

1

You can store the json creds returned by the authorization flow. The library will then be able to load those stored creds the next time it needs access.

The following example is adapted from the official Google drive quickstart

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']


def main():
    """Shows basic usage of the YouTube Analytics v2 API.
    
    """
    creds = None
    # The file token.json 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.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('youtubeAnalytics', 'v2', credentials=creds)

        # Call the YouTube analytics
         ...
        
    except HttpError as error:
        # TODO(developer) - Handle errors from API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

If you have any issues with this please let me know.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • 1
    Thank you for your answer, I decided to adopt your answer, json is much smaller than pickle, and this is the first time I know I can write `flow.run_local_server(port=0)`, which is very convenient for my own testing, but I Modified to `flow.run_console()` because I need to pass the URL to others – nike01705 Aug 25 '22 at 14:32
0

save it as a pkl file then call the file and update it

import pickle

dump into pkl file for first time and updates

with open('mypickle.pickle', 'wb') as f:
    pickle.dump(resource, f)

resource = whatever you want to store open file at later time

with open('mypickle.pickle', 'rb') as f:
    loaded_obj = pickle.load(f)
  • Welcome to stack. While your answer may technical be correct. It may not be very helpful to a user new to the api and this concept. It is better to fully explain what it is you are suggesting the user do. Adding links, or examples can be helpful as well. Please read [How to anwser](https://stackoverflow.com/help/how-to-answer) – Linda Lawton - DaImTo Aug 25 '22 at 10:42
  • @DaImTo is this better? – Benjamin Zatman Aug 25 '22 at 10:48
  • And how would you implement that using the google apis python client library? Which value returned by the library would you suggest the author store? The question is which object should be stored. not how to store it. – Linda Lawton - DaImTo Aug 25 '22 at 10:49
  • Thanks for your answer, I successfully saved "youtube_analytics" and read. However, when reading, you need to mark "rb" to read correctly `with open('mypickle.pickle', 'rb') as f:` – nike01705 Aug 25 '22 at 13:59