Python oauth2client 模块,file() 实例源码

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

项目:rube-gmail    作者:bonzini    | 项目源码 | 文件源码
def get_credentials(client_secret_file, credentials_file, scopes, user_agent, args=None):
    """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.
    """
    store = oauth2client.file.Storage(credentials_file)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_file, scopes)
        flow.user_agent = user_agent
        if args:
            credentials = oauth2client.tools.run_flow(flow, store, args)
        else: # Needed only for compatibility with Python 2.6
            credentials = oauth2client.tools.run(flow, store)
        print('Storing credentials to ' + credentials_file)
    return credentials



# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-import.json
项目:rube-gmail    作者:bonzini    | 项目源码 | 文件源码
def get_credentials(client_secret_file, credentials_file, scopes, user_agent, args=None):
    """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.
    """
    store = oauth2client.file.Storage(credentials_file)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_file, scopes)
        flow.user_agent = user_agent
        if args:
            credentials = oauth2client.tools.run_flow(flow, store, args)
        else: # Needed only for compatibility with Python 2.6
            credentials = oauth2client.tools.run(flow, store)
        print('Storing credentials to ' + credentials_file)
    return credentials



# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-import.json
项目:gmailtool    作者:adamandpaul    | 项目源码 | 文件源码
def cmd_auth(args):
    """The authentication command
    """
    logger.debug('Running command auth')

    credentials_storage_path = os.path.join(args.profile_dir, config.oauth_credentials_storage_filename)
    credentials_storage = oauth2client.file.Storage(credentials_storage_path)
    credentials = credentials_storage.get()
    if credentials is None or credentials.invalid:

        client_secret_file_handle, client_secret_path = tempfile.mkstemp()
        client_secret_fout = os.fdopen(client_secret_file_handle, 'w')
        json.dump(config.oauth_client_secret, client_secret_fout)
        client_secret_fout.close()
        flow = oauth2client.client.flow_from_clientsecrets(client_secret_path,
                                                           config.oauth_scopes)
        flow.user_agent = config.oauth_application_name
        credentials = oauth2client.tools.run_flow(flow, credentials_storage, args)
        os.remove(client_secret_path)

    return credentials
项目:pyGACustomDimensions    作者:analyticsftw    | 项目源码 | 文件源码
def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):
  """Get a service that communicates to a Google API.

  Args:
    api_name: The name of the api to connect to.
    api_version: The api version to connect to.
    scope: A list auth scopes to authorize for the application.
    key_file_location: The path to a valid service account p12 key file.
    service_account_email: The service account email address.

  Returns:
    A service that is connected to the specified API.
  """

  credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

  http = credentials.authorize(httplib2.Http())

  # Build the Google API service object.
  service = build(api_name, api_version, http=http)

  return service
项目:GoogleGmail-Skill    作者:jcasoft    | 项目源码 | 文件源码
def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    print("checking for cached credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'mycroft-gmail-skill.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
        print 'Storing credentials to ' + credential_dir
    print 'Your GMail Skill is now authenticated '
    else:
    print 'Loaded credentials for Gmail Skill from ' + credential_dir
    return credentials
项目:GoogleGmail-Skill    作者:jcasoft    | 项目源码 | 文件源码
def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    print("checking for cached credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'mycroft-gmail-skill.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
        print 'Storing credentials to ' + credential_dir
    print 'Your GMail Skill is now authenticated '
    else:
    print 'Loaded credentials for Gmail Skill from ' + credential_dir
    return credentials
项目:GoogleGmail-Skill    作者:jcasoft    | 项目源码 | 文件源码
def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    print("checking for cached credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'mycroft-gmail-skill.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
        print 'Storing credentials to ' + credential_dir
    print 'Your GMail Skill is now authenticated '
    else:
    print 'Loaded credentials for Gmail Skill from ' + credential_dir

    return credentials
项目:SNH48Live    作者:SNH48Live    | 项目源码 | 文件源码
def get_authenticated_http_client(args, oauth_scopes):
    if args is None:
        args = ArgumentParser().parse_args([])
    if isinstance(oauth_scopes, str):
        # Singleton
        oauth_scopes = [oauth_scopes]
    flow = oauth2client.client.flow_from_clientsecrets(
        CLIENT_SECRETS_FILE,
        scope=' '.join(f'https://www.googleapis.com/auth/{scope}' for scope in oauth_scopes),
        message=MISSING_CLIENT_SECRETS_MESSAGE,
    )
    oauth_credentials_file = CONFIGS_DIR / f'credentials-{",".join(oauth_scopes)}.json'
    storage = oauth2client.file.Storage(oauth_credentials_file)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = oauth2client.tools.run_flow(flow, storage, args)
    return credentials.authorize(httplib2.Http())
项目:GoogleCalendar-Skill    作者:jcasoft    | 项目源码 | 文件源码
def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    print("checking for cached credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'mycroft-googlecalendar-skill.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
        print 'Storing credentials to ' + credential_dir
    print 'Your Google Calendar Skill is now authenticated '
    else:
    print 'Loaded credentials for Google Calendar Skill from ' + credential_dir
    return credentials
项目:GoogleCalendarSkill    作者:jcasoft    | 项目源码 | 文件源码
def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    print("checking for cached credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'mycroft-googlecalendar-skill.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
        print 'Storing credentials to ' + credential_dir
    print 'Your Google Calendar Skill is now authenticated '
    else:
    print 'Loaded credentials for Google Calendar Skill from ' + credential_dir
    return credentials
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def message_if_missing(filename):
  """Helpful message to display if the CLIENT_SECRETS file is missing."""

  return _CLIENT_SECRETS_MESSAGE % filename
项目:pyGACustomDimensions    作者:analyticsftw    | 项目源码 | 文件源码
def main():
    # Refer to the config.py settings file for credentials
    service_account_email = config.apiSettings['service_account_email']
    key_file_location = config.apiSettings['key_file_location']

    print("Reading custom dimensions from property")
    scope = ['https://www.googleapis.com/auth/analytics.readonly']
    service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)

    print("Analyzing available accounts.")
    properties = service.management().webproperties().list(accountId='~all').execute()

    propertiesList = properties.get("items")
    for property in propertiesList:
        print ("Exporting:\t"+property["id"]+"\t"+property["name"])
        csvname = "exports/"+property["id"] + ".csv"
        pchunks = property["id"].split("-")
        dimensions = service.management().customDimensions().list(
              accountId=pchunks[1],
              webPropertyId=property["id"],
        ).execute()
        dimList = dimensions.get("items")
        with open(csvname, 'w', newline='') as csvfile:
            dimdump = csv.writer(csvfile, delimiter=",")
            dimdump.writerow(["Index","Scope","Name","Active"])
            for dimension in dimList:
                dimdump.writerow([str(dimension["index"]),dimension["scope"],dimension["name"],str(dimension["active"])])
    print ("\nDone.\n")
项目:pyGACustomDimensions    作者:analyticsftw    | 项目源码 | 文件源码
def main():
    # Refer to the config.py settings file for credentials
    service_account_email = config.apiSettings['service_account_email']
    key_file_location = config.apiSettings['key_file_location']
    sourceCSV = 'inputs/cdims20.csv'
    propertyId = input('Enter the property ID (in the format UA-XXXXXXXX-Y): ')
    separator = input('Which separator are you using in the CSV file? (,/;): ')
    accountBits = propertyId.split('-')
    accountId = accountBits[1]

    print("Updating custom dimensions from CSV")
    scope = ['https://www.googleapis.com/auth/analytics.edit']
    service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)

    with open(sourceCSV) as csvfile:
        numline = len(csvfile.readlines())
        csvfile.seek(0)
        myreader = csv.reader(csvfile, delimiter=separator)

        next(myreader)
        i = 0
        for row in myreader:
            customDimensionId = ("ga:dimension" + str(row[0]))
            newDim = service.management().customDimensions().update(
              accountId=accountId,
              webPropertyId=propertyId,
              customDimensionId= customDimensionId,
              body={  
                  'name':row[1],
                  'scope':row[2],
                  'active': row[3]
              }            
            ).execute()
            progress(i,numline)
            i += 1
        print ("\n\nDone.")
项目:appbackendapi    作者:codesdk    | 项目源码 | 文件源码
def get_id_token(client_secrets_file, extra_args):
    storage = oauth2client.file.Storage('credentials.dat')
    credentials = storage.get()

    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(
            client_secrets_file, scope='email')
        credentials = oauth2client.tools.run_flow(
            flow, storage, flags=extra_args)

    # The ID token is used by Cloud Endpoints, not the access token.
    id_token = credentials.token_response['id_token']

    return id_token
项目:appbackendapi    作者:codesdk    | 项目源码 | 文件源码
def get_id_token(client_secrets_file, extra_args):
    storage = oauth2client.file.Storage('credentials.dat')
    credentials = storage.get()

    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(
            client_secrets_file, scope='email')
        credentials = oauth2client.tools.run_flow(
            flow, storage, flags=extra_args)

    # The ID token is used by Cloud Endpoints, not the access token.
    id_token = credentials.token_response['id_token']

    return id_token
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def message_if_missing(filename):
  """Helpful message to display if the CLIENT_SECRETS file is missing."""

  return _CLIENT_SECRETS_MESSAGE % filename
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def message_if_missing(filename):
  """Helpful message to display if the CLIENT_SECRETS file is missing."""

  return _CLIENT_SECRETS_MESSAGE % filename
项目:GoogleGmail-Skill    作者:jcasoft    | 项目源码 | 文件源码
def config_file():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.mycroft')
    filename = os.path.join(credential_dir,'mycroft.conf')
    if os.path.isfile(filename):
        try:
            with open(filename, "r") as jsonFile:
                data = json.load(jsonFile, object_pairs_hook=OrderedDict)
                resultado = list(v for k,v in data.items() if "GoogleGmailSkill" in k.lower())
                if len(resultado) == 0: 
            print "Updating configuration file"
                    data["GoogleGmailSkill"]={"loginEnabled":False,"loginLevel":3,"maxResults":5,"time_format":12}
                    try:
                        with open(filename, "w") as jsonFile:
                            jsonFile.write(json.dumps(OrderedDict(data), indent=4, sort_keys=False))
                    except IOError as error:
                            print "Saving configuration file failed"
                            return False
                    time.sleep(10)
                else:
                    return data

        except IOError as error:
            print "Reading config file failed"
            return False
    else:
        print "Creating new Config file"
        data = {"GoogleGmailSkill":{"loginEnabled":False,"loginLevel":3,"maxResults":5,"time_format":12}}
        try:
            with open(filename, "w") as jsonFile:
                jsonFile.write(json.dumps(OrderedDict(data), indent=4, sort_keys=False))
        except IOError as error:
            print "Saving configuration file failed: "
            return False

        time.sleep(10)
项目:GoogleGmail-Skill    作者:jcasoft    | 项目源码 | 文件源码
def config_file():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.mycroft')
    filename = os.path.join(credential_dir,'mycroft.conf')
    if os.path.isfile(filename):
        try:
            with open(filename, "r") as jsonFile:
                data = json.load(jsonFile, object_pairs_hook=OrderedDict)
                resultado = list(v for k,v in data.items() if "GoogleGmailSkill" in k.lower())
                if len(resultado) == 0: 
            print "Updating configuration file"
                    data["GoogleGmailSkill"]={"loginEnabled":False,"loginLevel":3,"maxResults":5,"time_format":12}
                    try:
                        with open(filename, "w") as jsonFile:
                            jsonFile.write(json.dumps(OrderedDict(data), indent=4, sort_keys=False))
                    except IOError as error:
                            print "Saving configuration file failed"
                            return False
                    time.sleep(10)
                else:
                    return data

        except IOError as error:
            print "Reading config file failed"
            return False
    else:
        print "Creating new Config file"
        data = {"GoogleGmailSkill":{"loginEnabled":False,"loginLevel":3,"maxResults":5,"time_format":12}}
        try:
            with open(filename, "w") as jsonFile:
                jsonFile.write(json.dumps(OrderedDict(data), indent=4, sort_keys=False))
        except IOError as error:
            print "Saving configuration file failed: "
            return False

        time.sleep(10)
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
def message_if_missing(filename):
  """Helpful message to display if the CLIENT_SECRETS file is missing."""

  return _CLIENT_SECRETS_MESSAGE % filename
项目:pyGACustomDimensions    作者:analyticsftw    | 项目源码 | 文件源码
def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Refer to the config.py settings file for credentials
  service_account_email = config.apiSettings['service_account_email']
  key_file_location = config.apiSettings['key_file_location']

  propertyId = input('Enter the property ID (in the format UA-XXXXXXXX-Y): ')
  accountBits = propertyId.split('-')
  accountId = accountBits[1]
  isPremium = input('Is this a Premium property? (y/n): ')
  dimRange = 200 if isPremium == "y" else 20
  isActive = input('Leave all custom dimensions active? (y/n): ')
  dimActive = True if (isActive == "y") else False
  isType = input('Default dimension scope? (HIT, SESSION, USER, PRODUCT): ')

  # Authenticate and construct service.
  print("Connecting to Google Analytics API for authentication")
  service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)

  print("Pulling dimensions")
  dimensions = service.management().customDimensions().list(
    accountId=accountId,
    webPropertyId=propertyId
  ).execute()

  time.sleep(1)  
  nbDims = dimensions.get("totalResults")
  print("Found " + str(nbDims) + " custom dims")
  print("Updating custom dimensions")
  scope = ['https://www.googleapis.com/auth/analytics.edit']
  service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)
  for i in range(1,dimRange+1):
      # print("Deactivating custom dimension #"+ str(i))
      newDim = service.management().customDimensions().update(
        accountId=accountId,
        webPropertyId=propertyId,
        customDimensionId="ga:dimension" + str(i),
        body={
            'name':'Custom dimension #'+ str(i),
            'active': dimActive,
            'scope': isType
        }            
      ).execute()

      ''' Account for API quotas and pause every so often'''
      if i %10 == 0:
          time.sleep(5)
      progress(i,dimRange+1)
  print ("\n\nDone.")
项目:pyGACustomDimensions    作者:analyticsftw    | 项目源码 | 文件源码
def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Refer to the config.py settings file for credentials
  service_account_email = config.apiSettings['service_account_email']
  key_file_location = config.apiSettings['key_file_location']

  propertyId = input('Enter the property ID (in the format UA-XXXXXXXX-Y): ')
  accountBits = propertyId.split('-')
  accountId = accountBits[1]
  isPremium = input('Is this a Premium property? (y/n): ')
  dimRange = 200 if isPremium == "y" else 20
  isActive = input('Leave all custom dimensions active? (y/n): ')
  dimActive = True if (isActive == "y") else False
  isType = input('Default dimension scope? (HIT, SESSION, USER, PRODUCT): ')

  # Authenticate and construct service.
  print("Connecting to Google Analytics API for authentication")
  service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)

  print("Pulling dimensions")
  dimensions = service.management().customDimensions().list(
    accountId=accountId,
    webPropertyId=propertyId
  ).execute()

  time.sleep(10)  
  nbDims = dimensions.get("totalResults")
  print("Found " + str(nbDims) + " custom dims")
  if nbDims < dimRange+1:
      nbNewDims = dimRange - nbDims
      print("Creating " + str(nbNewDims) + " custom dimensions")
      scope = ['https://www.googleapis.com/auth/analytics.edit']
      service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)

      for i in range(nbDims+1,dimRange)
          newDim = service.management().customDimensions().insert(
            accountId=accountID,
            webPropertyId=propertyId,
            body={
                'name':"Spare custom dimension #"+ str(i),
                'scope': isType,
                'active': dimActive
            }            
          ).execute()
          if i %10 == 0:
              time.sleep(10)
          progress(i,nbNewDims)
      print "\n\nDone."