python类client()的实例源码

gam.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def doOAuthExport():
  if Cmd.ArgumentsRemaining():
    exportFile = getString(Cmd.OB_FILE_NAME)
    checkForExtraneousArguments()
  else:
    exportFile = None
  oauth2Export = {}
  if os.path.isfile(GC.Values[GC.OAUTH2_TXT]):
    for cred_family in API.FAM_LIST:
      credentials = getCredentialsForScope(cred_family)
      if credentials and not credentials.invalid:
        oauth2Export[cred_family] = {u'_module': u'oauth2client.client',
                                     u'_class': 'OAuth2Credentials',
                                     u'access_token': credentials.access_token,
                                     u'client_id': credentials.client_id,
                                     u'client_secret': credentials.client_secret,
                                     u'id_token': credentials.id_token,
                                     u'id_token_jwt': credentials.id_token_jwt,
                                     u'invalid': credentials.invalid,
                                     u'refresh_token': credentials.refresh_token,
                                     u'revoke_uri': credentials.revoke_uri,
                                     u'scopes': sorted(list(credentials.scopes)),
                                     u'token_expiry': datetime.datetime.strftime(credentials.token_expiry, u'%Y-%m-%dT%H:%M:%SZ'),
                                     u'token_info_uri': credentials.token_info_uri,
                                     u'token_uri': credentials.token_uri,
                                     u'user_agent': credentials.user_agent}
      else:
        invalidOauth2TxtExit()
  else:
    invalidOauth2TxtExit()
  if exportFile:
    writeFile(exportFile, json.dumps(oauth2Export, ensure_ascii=False, sort_keys=True, indent=2))
    entityModifierNewValueActionPerformed([Ent.OAUTH2_TXT_FILE, GC.Values[GC.OAUTH2_TXT]], Act.MODIFIER_TO, exportFile)
  else:
    writeStdout(json.dumps(oauth2Export, ensure_ascii=False, sort_keys=True, indent=2)+u'\n')

# gam oauth|oauth2 import <FileName>
gam.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def doOAuthImport():
  importFile = getString(Cmd.OB_FILE_NAME)
  checkForExtraneousArguments()
  jsonData = readFile(importFile, u'rb')
  try:
    jsonDict = json.loads(jsonData)
    if u'client_id' in jsonDict:
      importCredentials = oauth2client.client.Credentials.new_from_json(jsonData)
      if not importCredentials or importCredentials.invalid:
        invalidOauth2TxtImportExit(importFile)
      for cred_family in API.FAM_LIST:
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    elif (u'credentials' in jsonDict) and (jsonDict.get(u'file_version') == 2):
      for cred_family in API.FAM_LIST:
        importCredentials = getCredentialsForScope(cred_family, filename=importFile)
        if not importCredentials or importCredentials.invalid:
          invalidOauth2TxtImportExit(importFile)
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    elif (API.FAM1_SCOPES in jsonDict) and (API.FAM2_SCOPES in jsonDict):
      for cred_family in API.FAM_LIST:
        importCredentials = oauth2client.client.Credentials.new_from_json(json.dumps(jsonDict[cred_family], ensure_ascii=False, sort_keys=True))
        if not importCredentials or importCredentials.invalid:
          invalidOauth2TxtImportExit(importFile)
        getCredentialsForScope(cred_family, storageOnly=True).put(importCredentials)
    else:
      invalidOauth2TxtImportExit(importFile)
  except (KeyError, ValueError):
    invalidOauth2TxtImportExit(importFile)
  entityModifierNewValueActionPerformed([Ent.OAUTH2_TXT_FILE, GC.Values[GC.OAUTH2_TXT]], Act.MODIFIER_FROM, importFile)

# gam <UserTypeEntity> check serviceaccount
client.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def locked_get(self):
        """Retrieve credential.

        The Storage lock must be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        raise NotImplementedError
client.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def get(self):
        """Retrieve credential.

        The Storage lock must *not* be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        self.acquire_lock()
        try:
            return self.locked_get()
        finally:
            self.release_lock()
client.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def _get_application_default_credential_from_file(filename):
    """Build the Application Default Credentials from file."""
    # read the credentials from the file
    with open(filename) as file_obj:
        client_credentials = json.load(file_obj)

    credentials_type = client_credentials.get('type')
    if credentials_type == AUTHORIZED_USER:
        required_fields = set(['client_id', 'client_secret', 'refresh_token'])
    elif credentials_type == SERVICE_ACCOUNT:
        required_fields = set(['client_id', 'client_email', 'private_key_id',
                               'private_key'])
    else:
        raise ApplicationDefaultCredentialsError(
            "'type' field should be defined (and have one of the '" +
            AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")

    missing_fields = required_fields.difference(client_credentials.keys())

    if missing_fields:
        _raise_exception_for_missing_fields(missing_fields)

    if client_credentials['type'] == AUTHORIZED_USER:
        return GoogleCredentials(
            access_token=None,
            client_id=client_credentials['client_id'],
            client_secret=client_credentials['client_secret'],
            refresh_token=client_credentials['refresh_token'],
            token_expiry=None,
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent='Python client library')
    else:  # client_credentials['type'] == SERVICE_ACCOUNT
        from oauth2client import service_account
        return service_account._JWTAccessCredentials.from_json_keyfile_dict(
            client_credentials)
_auth.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def default_credentials():
    """Returns Application Default Credentials."""
    if HAS_GOOGLE_AUTH:
        credentials, _ = google.auth.default()
        return credentials
    elif HAS_OAUTH2CLIENT:
        return oauth2client.client.GoogleCredentials.get_application_default()
    else:
        raise EnvironmentError(
            'No authentication library is available. Please install either '
            'google-auth or oauth2client.')
docker_creds_.py 文件源码 项目:containerregistry 作者: google 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def password(self):
    # WORKAROUND...
    # The python oauth2client library only loads the credential from an
    # on-disk cache the first time 'refresh()' is called, and doesn't
    # actually 'Force a refresh of access_token' as advertised.
    # This call will load the credential, and the call below will refresh
    # it as needed.  If the credential is unexpired, the call below will
    # simply return a cache of this refresh.
    unused_at = self._creds.get_access_token(http=self._transport)

    # Most useful API ever:
    # https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={at}
    return self._creds.get_access_token(http=self._transport).access_token
django_orm.py 文件源码 项目:office-interoperability-tools 作者: milossramek 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Credentials):
      return value
    return pickle.loads(base64.b64decode(value))
django_orm.py 文件源码 项目:office-interoperability-tools 作者: milossramek 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def to_python(self, value):
    if value is None:
      return None
    if isinstance(value, oauth2client.client.Flow):
      return value
    return pickle.loads(base64.b64decode(value))
api.py 文件源码 项目:professional-services 作者: GoogleCloudPlatform 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, service, version):
        """Create a thread local API client.

        Will create the underlying httplib2.Http object on construction, but
        the underlying API client is lazy constructed.

        Args:
            service: Name of API.
            version: Version of the api.
        """
        self.service = service
        self.version = version
        self.http = httplib2.Http(timeout=60)
        self.cache_discovery = True
api.py 文件源码 项目:professional-services 作者: GoogleCloudPlatform 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __get__(self, instance, instance_type):
        """Construct the API client."""
        if instance is None:
            return self

        thread_local = None
        try:
            app = webapp2.get_app()
            # Python Google API clients aren't threadsafe as they use httplib2
            # which isn't threadsafe.
            thread_local = app.registry.get(self)
            if thread_local is None:
                thread_local = threading.local()
                app.registry[self] = thread_local
        except AssertionError:
            # When not in a request context, use class thread local.
            thread_local = ThreadsafeClientLocal._class_thread_local

        cached_client = getattr(thread_local, 'api', None)
        if cached_client is None:
            credentials = client.GoogleCredentials.get_application_default()
            if credentials.create_scoped_required():
                credentials = credentials.create_scoped(
                    'https://www.googleapis.com/auth/cloud-platform')
            cached_client = discovery.build(
                self.service,
                self.version,
                http=credentials.authorize(self.http),
                cache_discovery=self.cache_discovery)
            thread_local.api = cached_client
        return cached_client
client.py 文件源码 项目:hashtagtodo-open 作者: slackpad 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def retrieve_discovery_doc(serviceName, version,
                           discoveryServiceUrl=DISCOVERY_URI):
    params = {'api': serviceName, 'apiVersion': version}
    requested_url = uritemplate.expand(discoveryServiceUrl, params)

    # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
    # variable that contains the network address of the client sending the
    # request. If it exists then add that to the request for the discovery
    # document to avoid exceeding the quota on discovery requests.
    if 'REMOTE_ADDR' in os.environ:
        requested_url = _add_query_parameter(requested_url, 'userIp',
                                             os.environ['REMOTE_ADDR'])

    http = httplib2.Http()
    resp, content = http.request(requested_url)
    if resp.status >= 400:
        raise HttpError(resp, content, uri=requested_url)

    try:
        service = json.loads(content)
    except ValueError:
        raise InvalidJsonError(
            'Bad JSON: %s from %s.' % (content, requested_url))

    # We return content instead of the JSON deserialized service because
    # build_from_document() consumes a string rather than a dictionary.
    return content
client.py 文件源码 项目:hashtagtodo-open 作者: slackpad 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def make_client(user):
    credentials = AUTHOMATIC.credentials(user.credentials)

    # The token refresh will be a no-op if it's not due to expire soon.
    orig_token = credentials.token
    credentials.refresh(soon=TOKEN_REFRESH_SECONDS)
    if credentials.token != orig_token:
        user.credentials = credentials.serialize()
        user.put()

    # TODO - The code from here down will only work for Google clients. We
    # should generalize a bit.

    # The refresh here should never be used, but we add it here just so
    # requests will go through if we get into a weird state.
    oauth_credentials = oauth2client.client.OAuth2Credentials(
        access_token=credentials.token,
        client_id=credentials.consumer_key,
        client_secret=credentials.consumer_secret,
        refresh_token=credentials.refresh_token,
        token_expiry=credentials.expiration_date,
        token_uri=credentials.provider_class.access_token_url,
        user_agent=USER_AGENT)

    http = httplib2.Http()
    http = oauth_credentials.authorize(http)
    return DiscoveryDocument.build('calendar', 'v3', http=http)
boilercalendar.py 文件源码 项目:BoilerPlate 作者: wyaron 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_calendar_events(start_utc_time, end_utc_time, maxEvents=5):
  global service

  if service is None:
     init()
     authenticate()

  # did it work ? if not, the client of this class should retry
  if service is None:
     raise Exception('can not connect to google calendar')

  logging.getLogger('BoilerLogger').debug("Getting calendar events from: %s to %s" % (start_utc_time, end_utc_time))
  events = service.events().list(calendarId=CALENDAR_ID, orderBy="startTime",
                                 singleEvents=True, timeMin=start_utc_time, timeMax=end_utc_time, maxResults=maxEvents).execute()                
  return events['items']
test_sqlalchemy.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def setUp(self):
        engine = sqlalchemy.create_engine('sqlite://')
        Base.metadata.create_all(engine)

        self.session = sqlalchemy.orm.sessionmaker(bind=engine)
        self.credentials = oauth2client.client.OAuth2Credentials(
            access_token='token',
            client_id='client_id',
            client_secret='client_secret',
            refresh_token='refresh_token',
            token_expiry=datetime.datetime.utcnow(),
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent='DummyAgent',
        )
test_sqlalchemy.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_get(self, set_store):
        session = self.session()
        credentials_storage = oauth2client.contrib.sqlalchemy.Storage(
            session=session,
            model_class=DummyModel,
            key_name='key',
            key_value=1,
            property_name='credentials',
        )
        # No credentials stored
        self.assertIsNone(credentials_storage.get())

        # Invalid credentials stored
        session.add(DummyModel(
            key=1,
            credentials=oauth2client.client.Credentials(),
        ))
        session.commit()
        bad_credentials = credentials_storage.get()
        self.assertIsInstance(bad_credentials, oauth2client.client.Credentials)
        set_store.assert_not_called()

        # Valid credentials stored
        session.query(DummyModel).filter_by(key=1).delete()
        session.add(DummyModel(
            key=1,
            credentials=self.credentials,
        ))
        session.commit()

        self.compare_credentials(credentials_storage.get())
        set_store.assert_called_with(credentials_storage)
client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def locked_get(self):
        """Retrieve credential.

        The Storage lock must be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        raise NotImplementedError
client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get(self):
        """Retrieve credential.

        The Storage lock must *not* be held when this is called.

        Returns:
            oauth2client.client.Credentials
        """
        self.acquire_lock()
        try:
            return self.locked_get()
        finally:
            self.release_lock()
client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, access_token, client_id, client_secret, refresh_token,
                 token_expiry, token_uri, user_agent,
                 revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
        """Create an instance of GoogleCredentials.

        This constructor is not usually called by the user, instead
        GoogleCredentials objects are instantiated by
        GoogleCredentials.from_stream() or
        GoogleCredentials.get_application_default().

        Args:
            access_token: string, access token.
            client_id: string, client identifier.
            client_secret: string, client secret.
            refresh_token: string, refresh token.
            token_expiry: datetime, when the access_token expires.
            token_uri: string, URI of token endpoint.
            user_agent: string, The HTTP User-Agent to provide for this
                        application.
            revoke_uri: string, URI for revoke endpoint. Defaults to
                        oauth2client.GOOGLE_REVOKE_URI; a token can't be
                        revoked if this is None.
        """
        super(GoogleCredentials, self).__init__(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)
client.py 文件源码 项目:deb-python-oauth2client 作者: openstack 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def _get_application_default_credential_from_file(filename):
    """Build the Application Default Credentials from file."""
    # read the credentials from the file
    with open(filename) as file_obj:
        client_credentials = json.load(file_obj)

    credentials_type = client_credentials.get('type')
    if credentials_type == AUTHORIZED_USER:
        required_fields = set(['client_id', 'client_secret', 'refresh_token'])
    elif credentials_type == SERVICE_ACCOUNT:
        required_fields = set(['client_id', 'client_email', 'private_key_id',
                               'private_key'])
    else:
        raise ApplicationDefaultCredentialsError(
            "'type' field should be defined (and have one of the '" +
            AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")

    missing_fields = required_fields.difference(client_credentials.keys())

    if missing_fields:
        _raise_exception_for_missing_fields(missing_fields)

    if client_credentials['type'] == AUTHORIZED_USER:
        return GoogleCredentials(
            access_token=None,
            client_id=client_credentials['client_id'],
            client_secret=client_credentials['client_secret'],
            refresh_token=client_credentials['refresh_token'],
            token_expiry=None,
            token_uri=oauth2client.GOOGLE_TOKEN_URI,
            user_agent='Python client library')
    else:  # client_credentials['type'] == SERVICE_ACCOUNT
        from oauth2client import service_account
        return service_account._JWTAccessCredentials.from_json_keyfile_dict(
            client_credentials)


问题


面经


文章

微信
公众号

扫码关注公众号