Python oauth2client.tools.argparser() Examples
The following are 15
code examples of oauth2client.tools.argparser().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
oauth2client.tools
, or try the search function
.
Example #1
Source File: obtainGSToken.py From ingress-fieldplan with GNU General Public License v3.0 | 6 votes |
def main(): description = ( 'Obtain a Google Spreadsheets authorization token using credentials.json.' 'To obtain the credentials.json file, follow instructions on this page:' 'https://developers.google.com/sheets/api/quickstart/python' 'Save credentials.json in the same directory with this script.' ) parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args() home = str(Path.home()) cachedir = os.path.join(home, '.cache', 'ingress-fieldmap') Path(cachedir).mkdir(parents=True, exist_ok=True) tokenfile = os.path.join(cachedir, 'token.json') store = file.Storage(tokenfile) flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store, flags) if creds: print('Token saved in %s' % tokenfile)
Example #2
Source File: sheets_logger.py From imgcomp-cvpr with GNU General Public License v3.0 | 5 votes |
def main(): flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() check_connection(flags)
Example #3
Source File: google_drive.py From Packt-Publishing-Free-Learning with MIT License | 5 votes |
def _get_credentials(self): """ Get 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: the obtained credentials. """ home_dir = os.path.dirname(self.cfg_file_path) credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, '{}.json'.format(self.app_name)) store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(os.path.join(home_dir, CLIENT_SECRET_FILE), SCOPES) flow.user_agent = self.app_name parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser] ) flags = parser.parse_args(sys.argv[4:]) credentials = tools.run_flow(flow, store, flags) logger.success('Storing credentials to {}'.format(credential_path)) return credentials
Example #4
Source File: credentials.py From platypush with MIT License | 5 votes |
def generate_credentials(client_secret_path, scope): credentials_file = get_credentials_filename(*sorted(scope.split(' '))) store = Storage(credentials_file) flow = client.flow_from_clientsecrets(client_secret_path, scope) flow.user_agent = 'Platypush' flow.access_type = 'offline' flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() credentials = tools.run_flow(flow, store, flags) print('Storing credentials to ' + credentials_file)
Example #5
Source File: event1.py From pyrobotlab with Apache License 2.0 | 5 votes |
def event(): try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store, flags) \ if flags else tools.run(flow, store) CAL = build('calendar', 'v3', http=creds.authorize(Http())) SUBJECT = 'teste azul' GMT_OFF = '-04:00' EVENT = { 'summary' : SUBJECT, 'start' : {'dateTime': '2016-08-12T19:00:00%s' % GMT_OFF}, 'end' : {'dateTime': '2016-08-12T22:00:00%s' % GMT_OFF}, 'attendees': [ ], } e = CAL.events().insert(calendarId='primary', sendNotifications=True, body=EVENT).execute() print('''*** %r event added: Start: %s End: %s''' % (e['summary'].encode('utf-8'), e['start']['dateTime'], e['end']['dateTime']))
Example #6
Source File: auth.py From loaner with Apache License 2.0 | 4 votes |
def _request_new_credentials(self, scopes): """Create the user credentials without a local webserver. Args: scopes: List[str], a list of the required scopes for this credential. Returns: An instance of credentials.Credentials for the authenticated user. Raises: InvalidCredentials: when we are unable to get valid credentials for the user. """ redirect = 'urn:ietf:wg:oauth:2.0:oob' creds_flags = argparse.ArgumentParser( parents=[tools.argparser]).parse_args(['--noauth_local_webserver']) if _run_local_web_server_for_auth(): redirect = 'http://localhost:8080/oauth2callback' creds_flags = argparse.ArgumentParser( parents=[tools.argparser]).parse_args([ '--auth_host_port=8080', '--auth_host_name=localhost', ]) flow = oauth2_client.OAuth2WebServerFlow( client_id=self._config.client_id, client_secret=self._config.client_secret, scope=scopes, redirect_uri=redirect) try: old_credentials = tools.run_flow( flow, client_file.Storage(self._config.local_credentials_file_path), creds_flags) except oauth2_client.FlowExchangeError as err: raise InvalidCredentials( 'Unable to get valid credentials: {}.'.format(err)) if _remove_creds() and os.path.isfile( self._config.local_credentials_file_path): os.remove(self._config.local_credentials_file_path) return credentials.Credentials( token=old_credentials.access_token, refresh_token=old_credentials.refresh_token, id_token=old_credentials.id_token, token_uri=old_credentials.token_uri, client_id=old_credentials.client_id, client_secret=old_credentials.client_secret, scopes=list(old_credentials.scopes))
Example #7
Source File: sample_tools.py From splunk-ref-pas-code with Apache License 2.0 | 4 votes |
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)
Example #8
Source File: sample_tools.py From sndlatr with Apache License 2.0 | 4 votes |
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)
Example #9
Source File: sample_tools.py From twitter-for-bigquery with Apache License 2.0 | 4 votes |
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)
Example #10
Source File: utils.py From df2gspread with GNU General Public License v3.0 | 4 votes |
def get_credentials(credentials=None, client_secret_file=CLIENT_SECRET_FILE, refresh_token=None): """Consistently returns valid credentials object. See Also: https://developers.google.com/drive/web/quickstart/python Args: client_secret_file (str): path to client secrets file, defaults to .gdrive_private refresh_token (str): path to a user provided refresh token that is already pre-authenticated credentials (`~oauth2client.client.OAuth2Credentials`, optional): handle direct input of credentials, which will check credentials for valid type and return them Returns: `~oauth2client.client.OAuth2Credentials`: google credentials object """ # if the utility was provided credentials just return those if credentials: if _is_valid_credentials(credentials): # auth for gspread return credentials else: print("Invalid credentials supplied. Will generate from default token.") token = refresh_token or DEFAULT_TOKEN dir_name = os.path.dirname(DEFAULT_TOKEN) try: os.makedirs(dir_name) except OSError: if not os.path.isdir(dir_name): raise store = file.Storage(token) credentials = store.get() try: import argparse flags = argparse.ArgumentParser( parents=[tools.argparser]).parse_known_args()[0] except ImportError: flags = None logr.error( 'Unable to parse oauth2client args; `pip install argparse`') if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets( client_secret_file, SCOPES) flow.redirect_uri = client.OOB_CALLBACK_URN if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatability with Python 2.6 credentials = tools.run(flow, store) logr.info('Storing credentials to ' + DEFAULT_TOKEN) return credentials
Example #11
Source File: sample_tools.py From data with GNU General Public License v3.0 | 4 votes |
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)
Example #12
Source File: sample_tools.py From data with GNU General Public License v3.0 | 4 votes |
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)
Example #13
Source File: sample_tools.py From data with GNU General Public License v3.0 | 4 votes |
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)
Example #14
Source File: sample_tools.py From data with GNU General Public License v3.0 | 4 votes |
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)
Example #15
Source File: gmail2slack.py From gmail2slack with MIT License | 4 votes |
def __init__(self, config, slack): self.slack = slack self.config = config # Check https://developers.google.com/admin-sdk/directory/v1/guides/authorizing for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly' # Location of the credentials storage file STORAGE = Storage(self.config['gmail_storage']) # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(config['client_secret'], scope=OAUTH_SCOPE) http = httplib2.Http() # Try to retrieve credentials from storage or run the flow to generate them parser = argparse.ArgumentParser(parents=[tools.argparser]) flags = parser.parse_args([]) credentials = None storage = Storage(self.config['gmail2slack_oauth']) try: credentials = storage.get() except: sys.exit("Unable to retrieve credentials") if not credentials: credentials = tools.run_flow(flow, STORAGE, flags) storage.put(credentials) # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery self.gmail_service = build('gmail', 'v1', http=http) self.user_id = 'me' if 'gmail_label' in self.config: self.label_name = self.config['gmail_label'] else: self.label_name = 'INBOX' try: self.state = pickle.load(open(self.config['gmail2slack_pickle'], "rb")) except IOError: self.state = dict() self.state['timestamp'] = arrow.utcnow().timestamp # self.new_timestamp = arrow.utcnow().timestamp # BUG? Move to gmail2slack?