In python, is there any way I can store a 'Resource' object so I can use it later?

Question:

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

Asked By: nike01705

||

Answers:

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.

Answered By: DaImTo

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)
Answered By: Benjamin Zatman