Python oauth2client.tools 模块,argparser() 实例源码

我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用oauth2client.tools.argparser()

项目:gcp-tools    作者:lukwam    | 项目源码 | 文件源码
def auth_stored_credentials(self, client_secrets_file, scopes=[]):
        """Authorize stored credentials."""
        try:
            import argparse
            parser = argparse.ArgumentParser(parents=[tools.argparser])
            parser.add_argument('args', nargs=argparse.REMAINDER)
            flags = parser.parse_args()
            flags.noauth_local_webserver = True
        except ImportError:
            flags = None
        store = Storage(self.credentials_file)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(
                client_secrets_file,
                scopes,
            )
            flow.user_agent = self.app_name
            if flags:
                credentials = tools.run_flow(flow, store, flags)
            else:  # Needed only for compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print 'Saved credentials to ' + self.credentials_file
        return credentials
项目:ct_gdrive    作者:stanford-rc    | 项目源码 | 文件源码
def get_parser():
    """lhsm_gdrive command line options"""
    parser = argparse.ArgumentParser(add_help=False)
    # commands
    parser.add_argument('--action', choices=('pull', 'push'), required=True)
    # mandatory fd
    parser.add_argument('--fd', type=int, required=True)
    # mandatory Lustre fid
    parser.add_argument('--fid', required=True)
    # Lustre mount point
    parser.add_argument("--lustre-root", required=True)
    # Gdrive root ID
    parser.add_argument("--gdrive-root", required=True)
    # Credentials directory
    parser.add_argument("--creds-dir", required=True)

    return argparse.ArgumentParser(parents=[tools.argparser, parser])
项目:manage-maintenance    作者:colinmcintosh    | 项目源码 | 文件源码
def __init__(self):

        try:
            self._flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
            # Prevent a browser from opening
            self._flags.noauth_local_webserver = True
        except ImportError:
            self._flags = None

        ## Init logging
        self._logger = self.create_logger(logging_filename=LOGGING_FILE)
        logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

        ## Get credentials, build calendar service object
        mkdir_p(CREDENTIALS_DIR)
        credentials = self.get_credentials(CLIENT_SECRET_FILE, SCOPES, CREDENTIALS_DIR, CREDENTIALS_FILENAME)
        self._service = self.get_service(credentials)


        self.naive_find_event_overlap()
项目:LineBot    作者:RaenonX    | 项目源码 | 文件源码
def get_credentials():
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        import argparse

        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
        flags.noauth_local_webserver = True

        store = Storage(gmail_api.CREDENTIAL_FILE)
        credentials = store.get()

        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(gmail_api.CLIENT_SECRET_FILE, gmail_api.SCOPES)
            flow.user_agent = gmail_api.APPLICATION_NAME
            if flags:
                credentials = tools.run_flow(flow, store, flags)
            print 'Storing credentials to ' + gmail_api.CREDENTIAL_FILE

        return credentials
项目:libmozdata    作者:mozilla    | 项目源码 | 文件源码
def create_credentials(client_secret_path):
    """Gets valid user credentials from storage.

    Args:
        path (str), path to client_secret.json file
    """
    flow = client.flow_from_clientsecrets(client_secret_path, ' '.join(SCOPES))
    flow.user_agent = 'Clouseau'
    flow.params['access_type'] = 'offline'
    flow.params['approval_prompt'] = 'force'
    store = oauth2client.file.Storage(CREDENTIALS_PATH)
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args(['--noauth_local_webserver'])

    tools.run_flow(flow, store, flags)
项目:ct_gdrive    作者:stanford-rc    | 项目源码 | 文件源码
def get_parser():
    """ct_gdrive command line options"""
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--client-secret", required=True)
    # Credentials directory
    parser.add_argument("--creds-dir", required=True)

    return argparse.ArgumentParser(parents=[tools.argparser, parser])
项目:gdsync    作者:UUUM    | 项目源码 | 文件源码
def _create_credentials(self):
        store = oauth2client.file.Storage(self.credential_file)
        credentials = store.get()
        if not credentials or credentials.invalid:
            import argparse
            flags = argparse.ArgumentParser(
                parents=[tools.argparser]
            ).parse_args([])
            flow = client.flow_from_clientsecrets(
                self.client_secret_file,
                self.SCOPES
            )
            credentials = tools.run_flow(flow, store, flags)
        return credentials
项目:PyGsheet    作者:betomark    | 项目源码 | 文件源码
def __init__(self, app_name, spreadsheetId=None, with_pipeline=False):
        """Class parameters
        Args:
            spreadsheetId (str): id of spreadsheet (For: https://docs.google.com/spreadsheets/d/<spreadsheetId>/).
            app_name (str): Just a name for class instance.
        """
        self.app_name = app_name
        self.service = self.get_service()

        self.spreadsheetId = None
        if spreadsheetId:
            self.spreadsheetId = spreadsheetId
        else:
            self.create_spreadsheet(app_name)

        self.sheets_id = self.get_sheets_id()

        self.app_name = app_name
        self.flags = None
        try:
            import argparse
            self.flags = argparse.ArgumentParser(parents=[tools.argparser], conflict_handler='resolve').parse_args()
        except ImportError:
            self.flags = None

        self.with_pipeline = with_pipeline
        if self.with_pipeline:
            self.pipeline = []

        self.drive_manager = None
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def init(argv, name, version, doc, filename, scope=None, parents=[]):
  """A common initialization routine for samples.

  Many of the sample applications do the same initialization, which has now
  been consolidated into this function. This function uses common idioms found
  in almost all the samples, i.e. for an API with name 'apiname', the
  credentials are stored in a file named apiname.dat, and the
  client_secrets.json file is stored in the same directory as the application
  main file.

  Args:
    argv: list of string, the command-line parameters of the application.
    name: string, name of the API.
    version: string, version of the API.
    doc: string, description of the application. Usually set to __doc__.
    file: string, filename of the application. Usually set to __file__.
    parents: list of argparse.ArgumentParser, additional command-line flags.
    scope: string, The OAuth scope used.

  Returns:
    A tuple of (service, flags), where service is the service object and flags
    is the parsed command-line flags.
  """
  if scope is None:
    scope = 'https://www.googleapis.com/auth/' + name

  # Parser command-line arguments.
  parent_parsers = [tools.argparser]
  parent_parsers.extend(parents)
  parser = argparse.ArgumentParser(
      description=doc,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=parent_parsers)
  flags = parser.parse_args(argv[1:])

  # Name of a file containing the OAuth 2.0 information for this
  # application, including client_id and client_secret, which are found
  # on the API Access tab on the Google APIs
  # Console <http://code.google.com/apis/console>.
  client_secrets = os.path.join(os.path.dirname(filename),
                                'client_secrets.json')

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(client_secrets,
      scope=scope,
      message=tools.message_if_missing(client_secrets))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http = httplib2.Http())

  # Construct a service object via the discovery service.
  service = discovery.build(name, version, http=http)
  return (service, flags)
项目:HOTBot    作者:adammhaile    | 项目源码 | 文件源码
def run_script():
    # can use --noauth_local_webserver to manually auth
    parser = argparse.ArgumentParser(description='HOTBot automated event scheduler',
                                     parents=[tools.argparser])
    parser.add_argument(
        "--event",
        required=True,
        help="Event name (used as key for calendar lookup)")
    parser.add_argument(
        "--days",
        help="Number of days in the future to look for events (default: 7)",
        type=int,
        default=7)
    parser.add_argument(
        "--edit-guests", dest='edit_guests',
        default=False, action='store_true',
        help="Edit guests for event")
    parser.add_argument(
        "--edit-loc", dest='edit_loc',
        default=False, action='store_true',
        help="Edit locations for event")
    parser.add_argument(
        "--edit-msg", dest='edit_msg',
        default=False, action='store_true',
        help="Edit possible messages for event")
    parser.add_argument(
        "--select-cal", dest='select_cal',
        default=False, action='store_true',
        help="Select host calendar")
    parser.add_argument(
        "--ins-events", dest='ins_events',
        default=False, action='store_true',
        help="Insert event placeholders into calendar with cron formatting")
    flags = parser.parse_args()

    try:
        main(flags)
    except SystemExit:
        pass
    except:
        log.exception("Fatal error occured in script: ")
    finally:
        logging.shutdown()
项目:PyGsheet    作者:betomark    | 项目源码 | 文件源码
def get_credentials(self, cred_path):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        if not cred_path:
            home_dir = os.path.expanduser('~')
            credential_dir = os.path.join(home_dir, '.credentials')
            if not os.path.exists(credential_dir):
                try:
                    os.system("sudo mkdir {}".format(credential_dir))
                except:
                    os.umask(0)
                    os.makedirs(credential_dir, mode=0o777)
        else:
            credential_dir = cred_path
        credential_path = os.path.join(credential_dir,
                                       'python-quickstart.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.secret_file, scope=['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'])
            flow.user_agent = self.app_name
            try:
                import argparse
                flags = argparse.ArgumentParser(parents=[tools.argparser], conflict_handler='resolve').parse_args()
            except ImportError:
                flags = None
            try:
                credentials = tools.run_flow(flow, store, flags)
            except: # Needed only for compatibility with Python 2.6
                try:
                    credentials = tools.run_flow(flow, store)
                except:
                    credentials = tools.run(flow, store)
            print('Storing credentials to ' + credential_path)
        return credentials