Python oauth2client.service_account.ServiceAccountCredentials 模块,from_json_keyfile_name() 实例源码

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

项目:BoilerPlate    作者:wyaron    | 项目源码 | 文件源码
def authenticate():
    global service
    global http_auth
    global calendar

    try:
        # read credentials
        credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIAL_FILE_PATH, scopes)

    # authorize and get the calendar service
    http_auth = credentials.authorize(Http())
    service = discovery.build('calendar', 'v3', http=http_auth)
    calendar = service.calendars().get(calendarId=CALENDAR_ID).execute()
    except:
    logging.getLogger('BoilerLogger').error('failed to authenticate to google calendar service, will retry...')
    init()


# get calendar events in a window sorted by start time
项目:Coach    作者:Mirokoth    | 项目源码 | 文件源码
def on_message(self, message, command, arguments):
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_API, scope)
        gc = gspread.authorize(credentials)
        sheet = gc.open_by_url(GSHEET_URL)
        worksheet = sheet.get_worksheet(0)
        if arguments == False:
            await self.coach.forward_message(message.channel, "No command switches provided.")
        elif len(arguments) == 1:
            if arguments[0].upper() == "TEAMS":
                teams_output = ''
                teams = worksheet.col_values(1)
                for name in teams:
                    if len(name) > 1:
                        if name in teams_output or name == worksheet.acell('A1').value:
                            print(name)
                            pass
                        else:
                            teams_output += "{}\n".format(name)
                await self.coach.forward_message(message.channel, teams_output)
            else:
                await self.coach.forward_message(message.channel, 'Could not work with argument **{}**'.format(arguments[0]))
项目:kfusiontables    作者:kula1922    | 项目源码 | 文件源码
def build_service(self):
        """
        Build service for connect to google fusiontables.
        """

        logger.info('Build service for connect to google fusiontables server.')

        try:
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                self.PATH_TO_KEY,
                scopes=['https://www.googleapis.com/auth/fusiontables']
            )
            http_auth = credentials.authorize(Http())
        except IOError:
            raise IncorrectAccessFilePathException(
                "Access key path '{0}' is incorrect.".format(
                    self.PATH_TO_KEY
                )
            )

        self.SERVICE = build('fusiontables', 'v2', http=http_auth)
项目:docker-iot-calendar    作者:masterandrey    | 项目源码 | 文件源码
def get_credentials_http(self):
        if not os.path.isfile(self.settings[GOOGLE_CREDENTIALS_PARAM]):
            print('''Google API credentials file {} not found.
Get it on https://console.developers.google.com/start/api?id=calendar'''.format(
                self.settings[GOOGLE_CREDENTIALS_PARAM]
            ))
            return None
        try:
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                self.settings[GOOGLE_CREDENTIALS_PARAM],
                [
                    'https://www.googleapis.com/auth/calendar'
                ]
            )
        except Exception as e:
            print('''Cannot login to Google API - check your credential file {}.
You can get new one from https://console.developers.google.com/start/api?id=calendar'''.format(
                self.settings[GOOGLE_CREDENTIALS_PARAM]
            ))
            return None
        return credentials.authorize(httplib2.Http())
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def populate_spreadsheet():
    """Prerequisite: database is filled"""
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('metrictool-f16ab8f08d89.json', scope)
    conn = gspread.authorize(credentials)
    worksheet = conn.open("Metrics").sheet1

    worksheet.update_acell('A1', 'AUTHORS')
    worksheet.update_acell('B1', 'TITLES')
    worksheet.update_acell('C1', 'POST DATES')
    worksheet.update_acell('D1', 'VIEWS')
    worksheet.update_acell('E1', 'TAGS')
    worksheet.update_acell('F1', 'URL')

    row_index = 3 #1: header, 2: white space 
    for row in Post.select().order_by(-Post.post_date):
        cell_list = worksheet.range('A%s:F%s' % (row_index, row_index)) 
        cell_values = [row.author, row.title, row.post_date, row.views, row.tags, row.url]
        for i in range(len(cell_values)):
            cell_list[i].value = cell_values[i]
        row_index += 1
        worksheet.update_cells(cell_list)
项目:AutoUploaderGoogleDrive    作者:siorai    | 项目源码 | 文件源码
def Service_Account_Credential():
    """
    Utilizes the Service Account Credential flow to instantiate an authorized credentials
    object for calling the Google API
    """
    logging.debug('DEBUG: SAC_FLOW: Attemping to load settings file from %s' % settings.servicekeyfile)
    keyfile = settings.servicekeyfile
    logging.debug('DEBUG: SAC_FLOW: Finished loading Service Account Keyfile: using %s' % keyfile )
    logging.debug('DEBUG: SAC_FLOW: Loading scopes from settings file')
    scopes = settings.scopes
    logging.debug('DEBUG: SAC_FLOW: Finished loading scopes from settings file')
    logging.debug('DEBUG: SAC_FLOW: Initializing credential from oauth2client.service_account')
    credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, 
                        scopes=scopes)
    logging.debug('DEBUG: SAC_FLOW: Delegating credentials from settings')
    delegated_credentials = credentials.create_delegated(settings.delegated_email)
    logging.debug('DEBUG: SAC_FLOW:Initializing authorized, delegated credentials object')
    http = delegated_credentials.authorize(httplib2.Http())

    return http
项目:cloudaux    作者:Netflix-Skunkworks    | 项目源码 | 文件源码
def _googleauth(key_file=None, scopes=[], user_agent=None):
    """
    Google http_auth helper.

    If key_file is not specified, default credentials will be used.

    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES

    :param key_file: path to key file to use. Default is None
    :type key_file: ``str``

    :param scopes: scopes to set.  Default is DEFAUL_SCOPES
    :type scopes: ``list``

    :param user_agent: User Agent string to use in requests. Default is None.
    :type http_auth: ``str`` or None

    :return: HTTPLib2 authorized client.
    :rtype: :class: `HTTPLib2`
    """
    if key_file:
        if not scopes:
            scopes = DEFAULT_SCOPES
        creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,
                                                                 scopes=scopes)
    else:
        creds = GoogleCredentials.get_application_default()
    http = Http()
    if user_agent:
        http = set_user_agent(http, user_agent)
    http_auth = creds.authorize(http)
    return http_auth
项目:endpoints-tools    作者:cloudendpoints    | 项目源码 | 文件源码
def generate_jwt(args):
    """Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth"""
    # Make sure the service account has "Service Account Token Creator" permissions in Google IAM
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
      args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        serviceName='iam', version='v1', credentials=credentials)

    now = int(time.time())
    header_json = json.dumps({
        "typ": "JWT",
        "alg": "RS256"})

    payload_json = json.dumps({
        'iat': now,
        "exp": now + 3600,
        'iss': args.issuer if args.issuer else credentials.service_account_email,
        "target_audience": 'https://' + args.aud,
        "aud": "https://www.googleapis.com/oauth2/v4/token"
    })

    header_and_payload = '{}.{}'.format(
        base64.urlsafe_b64encode(header_json),
        base64.urlsafe_b64encode(payload_json))
    slist = service.projects().serviceAccounts().signBlob(
        name="projects/-/serviceAccounts/" + credentials.service_account_email,
        body={'bytesToSign': base64.b64encode(header_and_payload)})
    res = slist.execute()
    signature = base64.urlsafe_b64encode(
        base64.decodestring(res['signature']))
    signed_jwt = '{}.{}'.format(header_and_payload, signature)

    return signed_jwt
项目:endpoints-tools    作者:cloudendpoints    | 项目源码 | 文件源码
def main(args):
  """Generates a signed JSON Web Token using a Google API Service Account."""
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      args.service_account_file)

  now = int(time.time())

  payload = {
        "exp": now + credentials.MAX_TOKEN_LIFETIME_SECS,
        "iat": now,
        "aud": args.aud,
    }

  if args.email:
    payload["email"] = args.email
  if args.groupId:
    payload["groupId"] = args.groupId

  if args.issuer:
    payload["iss"] = args.issuer
    payload["sub"] = args.issuer
  else:
    payload["iss"] = credentials.service_account_email
    payload["sub"] = credentials.service_account_email

  signed_jwt = oauth2client.crypt.make_signed_jwt(
        credentials._signer, payload, key_id=credentials._private_key_id)

  return signed_jwt
项目:endpoints-tools    作者:cloudendpoints    | 项目源码 | 文件源码
def make_access_token(secret_token_json):
    """Construct an access token from service account token."""
    logging.info("Constructing an access token with scope " + _GOOGLE_API_SCOPE)
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        secret_token_json,
        scopes=[_GOOGLE_API_SCOPE])
    logging.info("Service account email: " + credentials.service_account_email)
    token = credentials.get_access_token().access_token
    return token
项目:project-status-dashboard    作者:cmheisel    | 项目源码 | 文件源码
def _load_via_api(sheet_id, sheet_auth_file):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(sheet_auth_file, ['https://spreadsheets.google.com/feeds'])
    sheetapi = gspread.authorize(credentials)
    worksheet = sheetapi.open_by_key(sheet_id).get_worksheet(0)
    csv = worksheet.export(format='csv')
    return parse_csv(csv.decode("utf-8"))
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def fetch(self, **kwargs):
        ''' Fetches an email using the Gmail API users.messages.get()
        method. It leverages the IsThisLegit service account to impersonate
        the user in order to retrieve the email by message ID. This prevents
        users from having to manually accept the OAuth permission dialog before
        reporting phishing emails.

        Expected kwargs:

        userId - The userID who reported the email
        messageId - The Gmail message ID to fetch
        '''
        userId = kwargs.get('userId')
        messageId = kwargs.get('messageId')

        scopes = ['https://www.googleapis.com/auth/gmail.readonly']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            config['gae']['service_account_key'], scopes=scopes)
        delegated_credentials = credentials.create_delegated(userId)
        http_auth = delegated_credentials.authorize(Http())
        service = build('gmail', 'v1', http=http_auth)
        response = service.users().messages().get(
            userId=userId, id=messageId, format='raw').execute()
        if not response or 'raw' not in response:
            raise EmailFetchError('Error fetching email: User {}, thread {}'.
                                  format(userId, messageId))
        message = base64.urlsafe_b64decode(str(response['raw']))
        return message
项目:kiwix-build    作者:kiwix    | 项目源码 | 文件源码
def __init__(self, options):
        scope = 'https://www.googleapis.com/auth/androidpublisher'
        key = options.google_api_key
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key,
            scopes=[scope])

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

        self.service = build('androidpublisher', 'v2', http=http)
        self.packageName = options.package_name
        self.edit_id = None
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __init__(self, account_json):

        scopes = ['https://www.googleapis.com/auth/ndev.clouddns.readwrite']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(account_json, scopes)
        self.dns = discovery.build('dns', 'v1', credentials=credentials, cache_discovery=False)
        with open(account_json) as account:
            self.project_id = json.load(account)['project_id']
项目:quickstart-python    作者:firebase    | 项目源码 | 文件源码
def _get_access_token():
  """Retrieve a valid access token that can be used to authorize requests.

  :return: Access token.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      'service-account.json', FCM_SCOPE)
  access_token_info = credentials.get_access_token()
  return access_token_info.access_token
# [END retrieve_access_token]
项目:SWProxy-plugins    作者:lstern    | 项目源码 | 文件源码
def get_worksheet(self, key, sheet):
        date = datetime.date.today()
        days_until_saturday = 5 - date.weekday()
        next_saturday = date + datetime.timedelta(days_until_saturday)

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(key, scope)
        gc = gspread.authorize(credentials)
        sheet_name = 'Guildwar %s' % next_saturday.strftime('%m-%d-%Y')
        return gc.open(sheet_name)
项目:nimbus    作者:kikinteractive    | 项目源码 | 文件源码
def run(self, search):
        """Entry point for the search. Iterate over VM's records."""
        from oauth2client.service_account import ServiceAccountCredentials
        from googleapiclient import discovery
        import glob
        import json
        import shutil
        scopes = ['https://www.googleapis.com/auth/compute.readonly']
        for filename in glob.glob(self.tmp_dir + '/*.json'):
            with open(filename) as data_file:
                data = json.load(data_file)
            project_id = data["project_id"]
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                filename, scopes=scopes)
            compute = discovery.build('compute', 'v1', credentials=credentials)
            zones = compute.zones()
            request = zones.list(project=project_id)
            filter = 'name eq {}.*'.format(search)
            while request is not None:
                response = request.execute()
                for zone in response['items']:
                    instances = compute.instances().list(
                        project=project_id, zone=zone['name'],
                        filter=filter).execute()
                    for instance in instances.get('items', []):
                        yield {
                            'Name': instance['name'],
                            'Zone': zone['name'],
                            'Project': project_id,
                            'Type': instance['machineType'].rsplit('/', 1)[-1]
                        }
                request = zones.list_next(previous_request=request,
                                          previous_response=response)
        shutil.rmtree(self.tmp_dir)
项目:RPoint    作者:george17-meet    | 项目源码 | 文件源码
def __init__(self, config):
        self.api_key = config["apiKey"]
        self.auth_domain = config["authDomain"]
        self.database_url = config["databaseURL"]
        self.storage_bucket = config["storageBucket"]
        self.credentials = None
        self.requests = requests.Session()
        if config.get("serviceAccount"):
            scopes = [
                'https://www.googleapis.com/auth/firebase.database',
                'https://www.googleapis.com/auth/userinfo.email',
                "https://www.googleapis.com/auth/cloud-platform"
            ]
            service_account_type = type(config["serviceAccount"])
            if service_account_type is str:
                self.credentials = ServiceAccountCredentials.from_json_keyfile_name(config["serviceAccount"], scopes)
            if service_account_type is dict:
                self.credentials = ServiceAccountCredentials.from_json_keyfile_dict(config["serviceAccount"], scopes)
        if is_appengine_sandbox():
            # Fix error in standard GAE environment
            # is releated to https://github.com/kennethreitz/requests/issues/3187
            # ProtocolError('Connection aborted.', error(13, 'Permission denied'))
            adapter = appengine.AppEngineAdapter(max_retries=3)
        else:
            adapter = requests.adapters.HTTPAdapter(max_retries=3)

        for scheme in ('http://', 'https://'):
            self.requests.mount(scheme, adapter)
项目:coscup-line-bot    作者:ncuoolab    | 项目源码 | 文件源码
def __init__(self, credential_path, spreadsheet_name):
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(credential_path, scope)
        self.gc = gspread.authorize(credentials)
        logging.info('Sheet service client authorized, credential path: %s' % credential_path)
        self.spreadsheet = self.gc.open(spreadsheet_name)
        pass
项目:decadegraphy    作者:decadegraphy    | 项目源码 | 文件源码
def _populate_google_calendar_http_handler(path_to_key_file: str):
    """Returns an authorized http handler instance for building the services.

    It takes an path to the service account key file.
    """
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        path_to_key_file, scopes=API_SCOPES)
    http_auth = credentials.authorize(Http())
    return http_auth
项目:wagalytics    作者:tomdyson    | 项目源码 | 文件源码
def get_access_token(ga_key_filepath):
    # from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
    # Defines a method to get an access token from the credentials object.
    # The access token is automatically refreshed if it has expired.

    # The scope for the OAuth2 request.
    SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

    # Construct a credentials objects from the key data and OAuth2 scope.
    _credentials = ServiceAccountCredentials.from_json_keyfile_name(
        ga_key_filepath, SCOPE)

    return _credentials.get_access_token().access_token
项目:heltour    作者:cyanfish    | 项目源码 | 文件源码
def _open_doc(url):
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(settings.GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH, scope)
    gc = gspread.authorize(credentials)
    try:
        return gc.open_by_url(url)
    except gspread.SpreadsheetNotFound:
        raise SpreadsheetNotFound
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def __init__(self):
        cred = ServiceAccountCredentials.from_json_keyfile_name(
            self.SERVICE_SECRET_FILE,
            self.scope)
        http = cred.authorize(httplib2.Http())

        self._client = build(self.service, self.version, http=http)
项目:DI_Sensors    作者:DexterInd    | 项目源码 | 文件源码
def login_open_sheet(oauth_key_file, spreadsheet):
    """Connect to Google Docs spreadsheet and return the first worksheet."""
    try:
        scope =  ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
        gc = gspread.authorize(credentials)
        worksheet = gc.open(spreadsheet).sheet1
        return worksheet
    except Exception as ex:
        print('Unable to login and get spreadsheet.  Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!')
        print('Google sheet login failed with error:', ex)
        sys.exit(1)
项目:spice-hate_speech_detection    作者:futurice    | 项目源码 | 文件源码
def create_google_sheet(sheetname):
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope)
    gc = gspread.authorize(credentials)

    wks = gc.create(sheetname).sheet1

    return wks
项目:spice-hate_speech_detection    作者:futurice    | 项目源码 | 文件源码
def get_access():
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope)
    gc = gspread.authorize(credentials)
    return gc
项目:lira    作者:HumanCellAtlas    | 项目源码 | 文件源码
def run(dss_url, key_file):
    scopes = ['https://www.googleapis.com/auth/userinfo.email']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
    h = credentials.authorize(Http())
    response, content = h.request(dss_url, 'GET')
    print(content)
项目:lira    作者:HumanCellAtlas    | 项目源码 | 文件源码
def run(dss_url, key_file):
    scopes = ['https://www.googleapis.com/auth/userinfo.email']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
    h = credentials.authorize(Http())
    response, content = h.request(dss_url, 'DELETE')
    print(content)
项目:lira    作者:HumanCellAtlas    | 项目源码 | 文件源码
def make_request(js, dss_url, key_file):
    scopes = ['https://www.googleapis.com/auth/userinfo.email']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
    h = credentials.authorize(Http())
    headers = {'Content-type': 'application/json'}
    response, content = h.request(dss_url, 'PUT', body=json.dumps(js), headers=headers)
    print(content)
项目:chirribackup    作者:killabytenow    | 项目源码 | 文件源码
def __init__(self, ldb, config = False):
        super(GoogleStorage, self).__init__(ldb, config)
        if not config:
            # okay .. not in config (ask_config() method)
            # load credentials and authenticate
            self.scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
            self.credentials = ServiceAccountCredentials.from_json_keyfile_name(
                                    self.ldb.sm_gs_json_creds_file,
                                    scopes=self.scopes)
            self.service = discovery.build('storage', 'v1', credentials=self.credentials)
项目:k8s-snapshots    作者:miracle2k    | 项目源码 | 文件源码
def get_gcloud(ctx, version: str= 'v1'):
    """
    Get a configured Google Compute API Client instance.

    Note that the Google API Client is not threadsafe. Cache the instance locally
    if you want to avoid OAuth overhead between calls.

    Parameters
    ----------
    version
        Compute API version
    """
    SCOPES = 'https://www.googleapis.com/auth/compute'
    credentials = None

    if ctx.config.get('gcloud_json_keyfile_name'):
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            ctx.config.get('gcloud_json_keyfile_name'),
            scopes=SCOPES)

    if ctx.config.get('gcloud_json_keyfile_string'):
        keyfile = json.loads(ctx.config.get('gcloud_json_keyfile_string'))
        credentials = ServiceAccountCredentials.from_json_keyfile_dict(
            keyfile, scopes=SCOPES)

    if not credentials:
        credentials = GoogleCredentials.get_application_default()

    if not credentials:
        raise RuntimeError("Auth for Google Cloud was not configured")

    compute = discovery.build(
        'compute',
        version,
        credentials=credentials,
        # https://github.com/google/google-api-python-client/issues/299#issuecomment-268915510
        cache_discovery=False
    )
    return compute
项目:necrobot    作者:incnone    | 项目源码 | 文件源码
def _get_credentials():
        if Spreadsheets.credentials is None:
            Spreadsheets.credentials = ServiceAccountCredentials.from_json_keyfile_name(
                filename=Config.OAUTH_CREDENTIALS_JSON,
                scopes=SCOPES
            )
项目:tf_face    作者:wwoo    | 项目源码 | 文件源码
def get_vision_service():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        os.path.join(resources.__path__[0], 'vapi-acct.json'), SCOPES)
    return discovery.build('vision', 'v1', credentials=credentials)
项目:tf_face    作者:wwoo    | 项目源码 | 文件源码
def get_cloudml_service():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        os.path.join(resources.__path__[0], 'vapi-acct.json'), SCOPES)
    return discovery.build('ml', 'v1', credentials=credentials)
项目:lemur    作者:apsknight    | 项目源码 | 文件源码
def reciever():
    # use creds to create a client to interact with the Google Drive API
    scope = ['https://spreadsheets.google.com/feeds']
    creds = ServiceAccountCredentials.from_json_keyfile_name('Lemur-key.json', scope)
    client = gspread.authorize(creds)
    sheet = client.open("Lemur Responses").sheet1

    receipents = filter(None, sheet.col_values(3)[1:])

    return receipents
项目:pygsheets    作者:nithinmurali    | 项目源码 | 文件源码
def authorize(outh_file='client_secret.json', outh_creds_store=None, outh_nonlocal=False, service_file=None,
              credentials=None, **client_kwargs):
    """Login to Google API using OAuth2 credentials.

    This function instantiates :class:`Client` and performs authentication.

    :param outh_file: path to outh2 credentials file, or tokens file
    :param outh_creds_store: path to directory where tokens should be stored
                           'global' if you want to store in system-wide location
                           None if you want to store in current script directory
    :param outh_nonlocal: if the authorization should be done in another computer,
                         this will provide a url which when run will ask for credentials
    :param service_file: path to service credentials file
    :param credentials: outh2 credentials object

    :param no_cache: (http client arg) do not ask http client to use a cache in tmp dir, useful for environments where
                     filesystem access prohibited
                     default: False

    :returns: :class:`Client` instance.

    """
    # @TODO handle exceptions
    if not credentials:
        if service_file:
            with open(service_file) as data_file:
                data = jload(data_file)
                print('service_email : '+str(data['client_email']))
            credentials = ServiceAccountCredentials.from_json_keyfile_name(service_file, SCOPES)
        elif outh_file:
            credentials = get_outh_credentials(client_secret_file=outh_file, credential_dir=outh_creds_store,
                                               outh_nonlocal=outh_nonlocal)
        else:
            raise AuthenticationError
    rclient = Client(oauth=credentials, **client_kwargs)
    return rclient


# @TODO
项目:ws-backend-community    作者:lavalamp-    | 项目源码 | 文件源码
def __create_signed_url_for_resource(
            self,
            verb="GET",
            bucket=None,
            file_key=None,
            duration=config.storage_signed_url_duration,
            creds_file_path=config.gcp_creds_file_path,
    ):
        """
        Create and return a signed URL for retrieving the specified file from GCP.
        :param verb: The HTTP verb for the signed request.
        :param bucket: The bucket where the file resides.
        :param file_key: The key where the file resides within the bucket.
        :param duration: The amount of time in seconds that the URL should be valid for.
        :param creds_file_path: The local file path to where the GCP credentials to use to sign
        the URL reside.
        :return: A signed URL that can be used to retrieve the referenced file's contents.
        """
        to_sign, expires_epoch = self.__get_signing_content_for_resource(
            verb=verb,
            bucket=bucket,
            file_key=file_key,
            duration=duration,
        )
        creds = ServiceAccountCredentials.from_json_keyfile_name(creds_file_path)
        client_id = creds.service_account_email
        signed_blob = creds.sign_blob(to_sign)[1]
        encoded_sig = b64encode(signed_blob).replace("+", "%2B").replace("/", "%2F")
        resource_url = "%s%s/%s" % (
            self.base_url,
            bucket,
            file_key,
        )
        return "%s?GoogleAccessId=%s&Expires=%s&Signature=%s" % (
            resource_url,
            client_id,
            expires_epoch,
            encoded_sig,
        )
项目:spinnaker-monitoring    作者:spinnaker    | 项目源码 | 文件源码
def make_stub(options):
  """Helper function for making a stub to talk to service."""
  if not stackdriver_available:
      raise ImportError(
          'You must "pip install google-api-python-client oauth2client" to get the stackdriver client library.')

  stackdriver_config = options.get('stackdriver', {})
  credentials_path = options.get('credentials_path', None)
  if credentials_path is None:
    credentials_path = stackdriver_config.get('credentials_path')
  if credentials_path:
    credentials_path = os.path.expandvars(credentials_path)

  http = httplib2.Http()
  http = apiclient.http.set_user_agent(
      http, 'SpinnakerStackdriverAgent/0.001')
  if credentials_path:
    logging.info('Using Stackdriver Credentials from "%s"', credentials_path)
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        credentials_path, scopes=StackdriverMetricsService.WRITE_SCOPE)
  else:
    logging.info('Using Stackdriver Credentials from application default.')
    credentials = GoogleCredentials.get_application_default()

  http = credentials.authorize(http)
  developer_key = os.environ.get('STACKDRIVER_API_KEY',
                                 options.get('stackdriver', {}).get('api_key'))
  if developer_key:
    url = 'https://monitoring.googleapis.com/$discovery/rest?labels=DASHBOARD_TRUSTED_TESTER&key=' + developer_key
    return apiclient.discovery.build(
        'monitoring', 'v3', http=http,
        discoveryServiceUrl=url)
  else:
    return apiclient.discovery.build('monitoring', 'v3', http=http)
项目:big-orm    作者:junyiacademy    | 项目源码 | 文件源码
def __init__(self, project_id, credential_path):
        self.credential_path = credential_path
        self.project_id = project_id
        scopes = ['https://www.googleapis.com/auth/bigquery']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            credential_path, scopes)
        http_auth = credentials.authorize(Http())
        bigquery = build('bigquery', 'v2', http=http_auth)
        self.bigquery = bigquery
项目:raw-data-repository    作者:all-of-us    | 项目源码 | 文件源码
def _get_authorized_http(self):
    if self.creds_file:
      credentials = ServiceAccountCredentials.from_json_keyfile_name(self.creds_file, [SCOPE])
      return credentials.authorize(httplib2.Http())
    else:
      return httplib2.Http()
项目:firecloud-tools    作者:broadinstitute    | 项目源码 | 文件源码
def main():
    # The main argument parser
    parser = DefaultArgsParser(description="Register a service account for use in FireCloud.")

    # Core application arguments
    parser.add_argument('-j', '--json_credentials', dest='json_credentials', action='store', required=True, help='Path to the json credentials file for this service account.')
    parser.add_argument('-e', '--owner_email', dest='owner_email', action='store', required=True, help='Email address of the person who owns this service account')

    args = parser.parse_args()

    from oauth2client.service_account import ServiceAccountCredentials
    scopes = ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(args.json_credentials, scopes=scopes)
    headers = {"Authorization": "bearer " + credentials.get_access_token().access_token}
    headers["User-Agent"] = firecloud_api.FISS_USER_AGENT

    uri = "https://api.firecloud.org/register/profile"

    profile_json = {"firstName":"None", "lastName": "None", "title":"None", "contactEmail":args.owner_email,
                               "institute":"None", "institutionalProgram": "None", "programLocationCity": "None", "programLocationState": "None",
                               "programLocationCountry": "None", "pi": "None", "nonProfitStatus": "false"}
    request = requests.post(uri, headers=headers, json=profile_json)

    if request.status_code == 200:
        print "The service account %s is now registered with FireCloud.  You can share workspaces with this address, or use it to call APIs." % credentials._service_account_email
    else:
        fail("Unable to register service account: %s" % request.text)
项目:python-flask-cms-app    作者:kdchang    | 项目源码 | 文件源码
def auth_gss_client(path, scopes):
    credentials = ServiceAccountCredentials.from_json_keyfile_name('webapp/auth.json', scopes)
    return gspread.authorize(credentials)
项目:pytablereader    作者:thombashi    | 项目源码 | 文件源码
def load(self):
        """
        Load table data from a Google Spreadsheet.

        This method consider :py:attr:`.source` as a path to the
        credential JSON file to access Google Sheets API.

        The method automatically search the header row start from
        :py:attr:`.start_row`. The condition of the header row is that
        all of the columns have value (except empty columns).

        :return:
            Loaded table data. Return one |TableData| for each sheet in
            the workbook. The table name for data will be determined by
            :py:meth:`~.GoogleSheetsTableLoader.make_table_name`.
        :rtype: iterator of |TableData|
        :raises pytablereader.InvalidDataError:
            If the header row is not found.
        :raises pytablereader.OpenError:
            If the spread sheet not found.
        """

        import gspread
        from oauth2client.service_account import ServiceAccountCredentials

        self._validate_table_name()
        self._validate_title()

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            self.source, scope)

        gc = gspread.authorize(credentials)
        try:
            for worksheet in gc.open(self.title).worksheets():
                self._worksheet = worksheet
                self.__all_values = [row for row in worksheet.get_all_values()]

                if self._is_empty_sheet():
                    continue

                try:
                    self.__strip_empty_col()
                except ValueError:
                    continue

                value_matrix = self.__all_values[self._get_start_row_idx():]
                try:
                    header_list = value_matrix[0]
                    record_list = value_matrix[1:]
                except IndexError:
                    continue

                self.inc_table_count()

                yield TableData(
                    self.make_table_name(), header_list, record_list,
                    quoting_flags=self.quoting_flags)
        except gspread.exceptions.SpreadsheetNotFound:
            raise OpenError("spreadsheet '{}' not found".format(self.title))
项目:SWProxy-plugins    作者:lstern    | 项目源码 | 文件源码
def save_row(self, csv_type, data_type, data):
        if data_type == 'entry':
            if csv_type == 'run_logger':
                tab = 'Runs'
                last_column = 'Y'
                total = 'AA1'
            elif csv_type == 'arena_logger':
                tab = 'Arena'
                last_column = 'P'
                total = 'R1'
            elif csv_type == 'summon_logger':
                tab = 'Summon'
                last_column = 'F'
                total = 'H1'
            elif csv_type == 'raid_logger':
                tab = 'Raid'
                last_column = 'K'
                total = 'M1'
            elif csv_type == 'worldboss_logger':
                tab = 'World Boss'
                last_column = 'AA'
                total = 'AC1'
            elif csv_type == 'toa_logger':
                tab = 'ToA'
                last_column = 'O'
                total = 'Q1'
            elif csv_type == 'guild_battle_logger':
                tab = 'Guild'
                last_column = 'S'
                total = 'U1'

            names, row = data
            key_file = self.config['google_key']
            sheet_name = self.config['sheet_name']
            scope = ['https://spreadsheets.google.com/feeds']
            credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scope)
            gc = gspread.authorize(credentials)
            wks = gc.open(sheet_name).worksheet(tab)
            line = int(wks.acell(total).value) + 2
            cl = wks.range('A%s:%s%s' % (line, last_column, line))
            for (i, name) in enumerate(names):
                if name in row:
                    cl[i].value = row[name]

            wks.update_cells(cl)
项目:gcp-tools    作者:lukwam    | 项目源码 | 文件源码
def auth(
            self,
            client_secrets_file=None,
            service_account_file=None,
            sub_account=None,
    ):
        """Athenticate with gcloud application-default credentials."""
        if client_secrets_file:
            credentials = self.auth_stored_credentials(
                client_secrets_file=client_secrets_file,
                scopes=self.scopes
            )

        elif service_account_file:
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                service_account_file,
                scopes=self.scopes,
            )
            if sub_account:
                credentials = credentials.create_delegated(sub_account)

        else:
            # get application-default credentials from gcloud
            credentials = GoogleCredentials.get_application_default()

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


        #
        # build the various services that we'll need
        #

        # admin directory
        self.admin = build('admin', 'directory_v1', credentials=credentials)

        # build a cloud billing API service
        self.billing = build('cloudbilling', 'v1', credentials=credentials)

        # build a compute API service
        self.compute = build('compute', 'v1', credentials=credentials)
        self.compute_alpha = build('compute', 'alpha', credentials=credentials)

        # build a cloud resource manager API service
        self.crm = build('cloudresourcemanager', 'v1', credentials=credentials)

        # build an iam API service
        self.iam = build('iam', 'v1', credentials=credentials)

        # build a service management API service
        self.smgt = build('servicemanagement', 'v1', credentials=credentials)

        # build a service management API service
        self.storage = build('storage', 'v1', credentials=credentials)
项目:clusterfuzz-tools    作者:google    | 项目源码 | 文件源码
def send_log(params, stacktrace=None):
  """Joins the params dict with info like user id and then sends logs."""
  scopes = ['https://www.googleapis.com/auth/logging.write']
  filename = common.get_resource(
      0640, 'resources', 'clusterfuzz-tools-logging.json')

  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      filename, scopes=scopes)

  http_auth = credentials.authorize(Http())

  params['version'] = common.get_version()
  params['user'] = os.environ.get('USER')
  params['sessionId'] = get_session_id()
  if 'success' in params:
    prefix = ('successfully finished' if params['success'] else
              'unsuccessfully finished')
  else:
    prefix = 'started'

  props = [str(params['testcase_id'])]

  if params['current']:
    props.append('current')

  if params['enable_debug']:
    props.append('debug')

  params['message'] = '%s %s (%s, %s).' % (
      params['user'], prefix, params['command'], ', '.join(props))
  if stacktrace:
    params['message'] += '\n%s' % stacktrace

  structure = {
      'logName': 'projects/clusterfuzz-tools/logs/client',
      'resource': {
          'type': 'project',
          'labels': {
              'project_id': 'clusterfuzz-tools'}},
      'entries': [{
          'jsonPayload': params,
          'severity': 'ERROR' if stacktrace else 'INFO'}]}

  http_auth.request(
      uri='https://logging.googleapis.com/v2/entries:write',
      method='POST',
      body=json.dumps(structure))