當前位置: 首頁>>代碼示例>>Python>>正文


Python ServiceAccountCredentials.from_json_keyfile_name方法代碼示例

本文整理匯總了Python中oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name方法的典型用法代碼示例。如果您正苦於以下問題:Python ServiceAccountCredentials.from_json_keyfile_name方法的具體用法?Python ServiceAccountCredentials.from_json_keyfile_name怎麽用?Python ServiceAccountCredentials.from_json_keyfile_name使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在oauth2client.service_account.ServiceAccountCredentials的用法示例。


在下文中一共展示了ServiceAccountCredentials.from_json_keyfile_name方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _init_gsheet_client

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def _init_gsheet_client():
        with GoogleSheet._client_lock():
            def _():
                if config.GOOGLE_SERVICE_ACCOUNT is not None:
                    credentials = ServiceAccountCredentials.from_json_keyfile_dict(
                        json.loads(config.GOOGLE_SERVICE_ACCOUNT),
                        scopes=SCOPES)
                else:
                    credentials = ServiceAccountCredentials.from_json_keyfile_name(
                        "avrae-google.json",
                        scopes=SCOPES)
                return gspread.authorize(credentials)

            try:
                GoogleSheet.g_client = await asyncio.get_event_loop().run_in_executor(None, _)
            except:
                GoogleSheet._client_initializing = False
                raise
        GoogleSheet._token_expiry = datetime.datetime.now() + datetime.timedelta(
            seconds=ServiceAccountCredentials.MAX_TOKEN_LIFETIME_SECS)
        log.info("Logged in to google") 
開發者ID:avrae,項目名稱:avrae,代碼行數:23,代碼來源:gsheet.py

示例2: __init__

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def __init__(self,
                 project_id,
                 service_cred_path=None,
                 logger=None,
                 metrics=None,
                 **options):
        self.project_id = project_id
        self.endpoint = ("https://fcm.googleapis.com/v1/"
                         "projects/{}/messages:send".format(self.project_id))

        self.token = None
        self.metrics = metrics
        self.logger = logger or Logger()
        self._options = options
        if service_cred_path:
            self.svc_cred = ServiceAccountCredentials.from_json_keyfile_name(
                service_cred_path,
                ["https://www.googleapis.com/auth/firebase.messaging"])
        self._sender = treq.post 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:21,代碼來源:fcmv1client.py

示例3: get_service_object

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def get_service_object(self, name):
        service = GoogleAnalyticsHook._services[name]

        if self.connection.password:
            credentials = AccessTokenCredentials(self.connection.password,
                                                 'Airflow/1.0')
        elif hasattr(self, 'client_secrets'):
            credentials = ServiceAccountCredentials.from_json_keyfile_dict(self.client_secrets,
                                                                           service.scopes)

        elif hasattr(self, 'file_location'):
            credentials = ServiceAccountCredentials.from_json_keyfile_name(self.file_location,
                                                                           service.scopes)
        else:
            raise ValueError('No valid credentials could be found')

        return build(service.name, service.version, credentials=credentials) 
開發者ID:airflow-plugins,項目名稱:google_analytics_plugin,代碼行數:19,代碼來源:google_analytics_hook.py

示例4: handle

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def handle(self, *args, **options):
        """Fetch Mess Menus."""

        # Use credentials to create a client to interact with the Google Drive API
        print("Authorizing - ", end="", flush=True)
        scope = ['https://spreadsheets.google.com/feeds',
                 'https://www.googleapis.com/auth/drive']

        creds = ServiceAccountCredentials.from_json_keyfile_name('google_client_secret.json', scope)
        client = gspread.authorize(creds)
        print("OK")

        # Iterate over all hostels
        for hostel in Hostel.objects.all():
            print("Updating " + hostel.name + " - ", end="", flush=True)
            if hostel.mess_gsheet:
                try:
                    fetch_hostel(client, hostel)
                    print("OK")
                except Exception:  # pylint: disable=W0703
                    print("FAIL")
            else:
                print("SKIP") 
開發者ID:wncc,項目名稱:instiapp-api,代碼行數:25,代碼來源:mess_chore.py

示例5: get_access_token

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def get_access_token(ga_key_filepath):
    """Get the access token for Google Analytics.

    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 
開發者ID:tomdyson,項目名稱:wagalytics,代碼行數:18,代碼來源:views.py

示例6: upload_test_results

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def upload_test_results(results, name, sheet, credentials):
    """Upload the test results to the the google sheet"""

    if not sheet:
        return
    if not results:
        print('ERROR: No results specified')
        return

    credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials, SCOPES)
    gcloud = gspread.authorize(credentials)

    spreadsheet = gcloud.open_by_url(sheet)

    try:
        worksheet = spreadsheet.worksheet(results["suite"])
    except gspread.exceptions.WorksheetNotFound:
        print(" * ERROR: Worksheet {} not found".format(results["suite"]))
        return

    filename = "{}_{}_{}.json".format(name, results.get('suite'), results.get('timestamp'))

    gsheets_import(results, worksheet, filename) 
開發者ID:AMWA-TV,項目名稱:nmos-testing,代碼行數:25,代碼來源:runTestSuites.py

示例7: make_access_token

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
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 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:11,代碼來源:fetch_service_config.py

示例8: generate_jwt

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
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 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:36,代碼來源:generate-google-id-jwt.py

示例9: main

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
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 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:31,代碼來源:generate-jwt.py

示例10: _open_doc

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
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 
開發者ID:cyanfish,項目名稱:heltour,代碼行數:11,代碼來源:spreadsheet.py

示例11: get_service_acct_creds

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def get_service_acct_creds(key_file, verbose=False):
  '''Generate service account credentials using the given key file.
    key_file: path to file containing private key.
  '''
  ### backcompatability for .p12 keyfiles
  if key_file.endswith('.p12') or key_file.endswith('.pem'):
    from edx2bigquery_config import auth_service_acct as SERVICE_ACCT
    if verbose:
      print "using key file"
      print "service_acct=%s, key_file=%s" % (SERVICE_ACCT, KEY_FILE)
    try:
      creds = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCT,
        key_file,
        scopes=BIGQUERY_SCOPE)
    except Exception as err:			# fallback to old google SignedJwtAssertionCredentials call
      with open (key_file, 'rb') as f:
        key = f.read();
        creds = SignedJwtAssertionCredentials(
          SERVICE_ACCT, 
          key,
          BIGQUERY_SCOPE)
    return creds
  ###
  creds = ServiceAccountCredentials.from_json_keyfile_name(
    key_file,
    BIGQUERY_SCOPE)
  return creds 
開發者ID:mitodl,項目名稱:edx2bigquery,代碼行數:30,代碼來源:auth.py

示例12: get_firebase_access_token

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def get_firebase_access_token(config_file_name):
    """
    This returns the access token for a given JSON config file name

    :param config_file_name:
    :return:
    """
    fbt = "firebase_token"
    now = time.time()
    app_store = get_app_local_store()

    if fbt not in app_store or not isinstance(app_store[fbt], dict):
        # initialize the firebase_token in the app_store as dict
        app_store[fbt] = {}

    if not isinstance(app_store[fbt].get(config_file_name), AccessToken) or \
            now > app_store[fbt].get(config_file_name).expires_at:
        # If the type of the config is not class AccessToken or
        # if the token has expired
        credentials = ServiceAccountCredentials.from_json_keyfile_name(config_file_name, SCOPES)
        log.debug("Fetching a new access_token for {!r} from firebase...".format(config_file_name))
        access_token_info = credentials.get_access_token()
        # Now we set the expiration date for the new access_token with a margin of 10 seconds
        At = AccessToken(access_token_info.access_token, access_token_info.expires_in)
        # We do not use a lock here: The worst that could happen is that two threads
        # fetch new auth tokens concurrently. In this case, one of them wins and is written to the dictionary.
        app_store[fbt][config_file_name] = At
        readable_time = datetime.datetime.fromtimestamp(At.expires_at).isoformat()
        log.debug(u"Setting the expiration for {!r} of the new access_token to {!s}.".format(config_file_name, readable_time))

    return app_store[fbt][config_file_name].access_token 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:33,代碼來源:FirebaseProvider.py

示例13: __init__

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def __init__(self, spreadsheet_name):
        self.item_col = 1
        self.price_col = 2
        self.frequency_col = 3
        self.url_col = 4
        self.product_name_col = 5
        
        scope = ['https://spreadsheets.google.com/feeds',
                 'https://www.googleapis.com/auth/drive']

        creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',
                                                                 scope)
        client = gspread.authorize(creds)

        self.sheet = client.open(spreadsheet_name).sheet1 
開發者ID:vprusso,項目名稱:youtube_tutorials,代碼行數:17,代碼來源:price_updater.py

示例14: fetch

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
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 
開發者ID:duo-labs,項目名稱:isthislegit,代碼行數:30,代碼來源:email.py

示例15: get_Auth

# 需要導入模塊: from oauth2client.service_account import ServiceAccountCredentials [as 別名]
# 或者: from oauth2client.service_account.ServiceAccountCredentials import from_json_keyfile_name [as 別名]
def get_Auth():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(cfg.CREDENTIAL_SERVICE, cfg.DEFAULT_SCOPES)
    http = httplib2.Http(memcache, timeout=60)
    #http = httplib2.Http()
    return credentials.authorize(http) 
開發者ID:jroakes,項目名稱:gsc-logger,代碼行數:7,代碼來源:utils_auth.py


注:本文中的oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。