Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
sample_tools.py109 linesDownload Raw Back to googleapiclient
1# Copyright 2014 Google Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#      http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15"""Utilities for making samples.16 17Consolidates a lot of code commonly repeated in sample applications.18"""19from __future__ import absolute_import20 21__author__ = "jcgregorio@google.com (Joe Gregorio)"22__all__ = ["init"]23 24 25import argparse26import os27 28from googleapiclient import discovery29from googleapiclient.http import build_http30 31 32def init(33    argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None34):35    """A common initialization routine for samples.36 37    Many of the sample applications do the same initialization, which has now38    been consolidated into this function. This function uses common idioms found39    in almost all the samples, i.e. for an API with name 'apiname', the40    credentials are stored in a file named apiname.dat, and the41    client_secrets.json file is stored in the same directory as the application42    main file.43 44    Args:45      argv: list of string, the command-line parameters of the application.46      name: string, name of the API.47      version: string, version of the API.48      doc: string, description of the application. Usually set to __doc__.49      file: string, filename of the application. Usually set to __file__.50      parents: list of argparse.ArgumentParser, additional command-line flags.51      scope: string, The OAuth scope used.52      discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL.53 54    Returns:55      A tuple of (service, flags), where service is the service object and flags56      is the parsed command-line flags.57    """58    try:59        from oauth2client import client, file, tools60    except ImportError:61        raise ImportError(62            "googleapiclient.sample_tools requires oauth2client. Please install oauth2client and try again."63        )64 65    if scope is None:66        scope = "https://www.googleapis.com/auth/" + name67 68    # Parser command-line arguments.69    parent_parsers = [tools.argparser]70    parent_parsers.extend(parents)71    parser = argparse.ArgumentParser(72        description=doc,73        formatter_class=argparse.RawDescriptionHelpFormatter,74        parents=parent_parsers,75    )76    flags = parser.parse_args(argv[1:])77 78    # Name of a file containing the OAuth 2.0 information for this79    # application, including client_id and client_secret, which are found80    # on the API Access tab on the Google APIs81    # Console <http://code.google.com/apis/console>.82    client_secrets = os.path.join(os.path.dirname(filename), "client_secrets.json")83 84    # Set up a Flow object to be used if we need to authenticate.85    flow = client.flow_from_clientsecrets(86        client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)87    )88 89    # Prepare credentials, and authorize HTTP object with them.90    # If the credentials don't exist or are invalid run through the native client91    # flow. The Storage object will ensure that if successful the good92    # credentials will get written back to a file.93    storage = file.Storage(name + ".dat")94    credentials = storage.get()95    if credentials is None or credentials.invalid:96        credentials = tools.run_flow(flow, storage, flags)97    http = credentials.authorize(http=build_http())98 99    if discovery_filename is None:100        # Construct a service object via the discovery service.101        service = discovery.build(name, version, http=http)102    else:103        # Construct a service object using a local discovery document file.104        with open(discovery_filename) as discovery_file:105            service = discovery.build_from_document(106                discovery_file.read(), base="https://www.googleapis.com/", http=http107            )108    return (service, flags)109 
codekingpro/portable-devtools · Team Ai