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


Python requests.Request方法代碼示例

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


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

示例1: getCreds

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def getCreds():
  # The file token.pickle stores the user's access and refresh tokens, and is
  # created automatically when the authorization flow completes for the first
  # time.
  creds = None
  SCOPES = 'https://www.googleapis.com/auth/drive'

  if os.path.exists('token.pickle'):
      with open('token.pickle', 'rb') as token:
          creds = pickle.load(token)
  # If there are no (valid) credentials available, let the user log in.
  if not creds or not creds.valid:
      if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
      else:
          flow = InstalledAppFlow.from_client_secrets_file(
              'credentials.json', SCOPES)
          creds = flow.run_local_server(port=0)
      # Save the credentials for the next run
      with open('token.pickle', 'wb') as token:
          pickle.dump(creds, token)

  return creds 
開發者ID:zume2020,項目名稱:Telegram-bot-Google-Drive,代碼行數:25,代碼來源:bot.py

示例2: logout

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def logout(user_name: str):
    """Logs out the user, removing their stored credentials and revoking the
    grant

    Args:
        user_name (str): The identifier of the user.
    """
    store = Store()
    user_credentials = store.get_user_credentials(user_name)
    if user_credentials is None:
        logging.info('Ignoring logout request for user %s', user_name)
        return
    logging.info('Logging out user %s', user_name)
    store.delete_user_credentials(user_name)
    request = requests.Request()
    request.post(
        'https://accounts.google.com/o/oauth2/revoke',
        params={'token': user_credentials.token},
        headers={'Content-Type': 'application/x-www-form-urlencoded'}) 
開發者ID:gsuitedevs,項目名稱:hangouts-chat-samples,代碼行數:21,代碼來源:auth.py

示例3: credentials

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def credentials(self) -> dict:
        if self._credentials is None:
            if not os.path.exists(self.credentials_path):
                raise ValueError(f"{self.credentials_path}: no such file or directory")
        
            if os.path.exists(self.token_path):
                with open(self.token_path, "rb") as fp:
                    self._credentials = pickle.load(fp)

            if not self._credentials or not self._credentials.valid:
                if self._credentials and self._credentials.expired and self._credentials.refresh_token:
                    self._credentials.refresh(transport.Request())
                else:
                    flow = oauthflow.InstalledAppFlow.from_client_secrets_file(self.credentials_path, self.scopes)
                    self._credentials = flow.run_local_server()
                
                with open(self.token_path, "wb") as fp:
                    pickle.dump(self._credentials, fp)
        return self._credentials 
開發者ID:BnetButter,項目名稱:hwk-mirror,代碼行數:21,代碼來源:api.py

示例4: test_default_state

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def test_default_state(self, get):
        get.side_effect = [
            {"email": "service-account@example.com", "scope": ["one", "two"]}
        ]

        request = mock.create_autospec(transport.Request, instance=True)
        self.credentials = credentials.IDTokenCredentials(
            request=request, target_audience="https://example.com"
        )

        assert not self.credentials.valid
        # Expiration hasn't been set yet
        assert not self.credentials.expired
        # Service account email hasn't been populated
        assert self.credentials.service_account_email == "service-account@example.com"
        # Signer is initialized
        assert self.credentials.signer
        assert self.credentials.signer_email == "service-account@example.com" 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:20,代碼來源:test_credentials.py

示例5: test_with_service_account

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def test_with_service_account(self, sign, get, utcnow):
        sign.side_effect = [b"signature"]

        request = mock.create_autospec(transport.Request, instance=True)
        self.credentials = credentials.IDTokenCredentials(
            request=request,
            target_audience="https://audience.com",
            service_account_email="service-account@other.com",
        )

        # Generate authorization grant:
        token = self.credentials._make_authorization_grant_assertion()
        payload = jwt.decode(token, verify=False)

        # The JWT token signature is 'signature' encoded in base 64:
        assert token.endswith(b".c2lnbmF0dXJl")

        # Check that the credentials have the token and proper expiration
        assert payload == {
            "aud": "https://www.googleapis.com/oauth2/v4/token",
            "exp": 3600,
            "iat": 0,
            "iss": "service-account@other.com",
            "target_audience": "https://audience.com",
        } 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:27,代碼來源:test_credentials.py

示例6: test_refresh_error

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def test_refresh_error(self, sign, get, utcnow):
        get.side_effect = [
            {"email": "service-account@example.com", "scopes": ["one", "two"]}
        ]
        sign.side_effect = [b"signature"]

        request = mock.create_autospec(transport.Request, instance=True)
        response = mock.Mock()
        response.data = b'{"error": "http error"}'
        response.status = 500
        request.side_effect = [response]

        self.credentials = credentials.IDTokenCredentials(
            request=request, target_audience="https://audience.com"
        )

        with pytest.raises(exceptions.RefreshError) as excinfo:
            self.credentials.refresh(request)

        assert excinfo.match(r"http error") 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:22,代碼來源:test_credentials.py

示例7: test_sign_bytes

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def test_sign_bytes(self, sign, get):
        get.side_effect = [
            {"email": "service-account@example.com", "scopes": ["one", "two"]}
        ]
        sign.side_effect = [b"signature"]

        request = mock.create_autospec(transport.Request, instance=True)
        response = mock.Mock()
        response.data = b'{"signature": "c2lnbmF0dXJl"}'
        response.status = 200
        request.side_effect = [response]

        self.credentials = credentials.IDTokenCredentials(
            request=request, target_audience="https://audience.com"
        )

        # Generate authorization grant:
        signature = self.credentials.sign_bytes(b"some bytes")

        # The JWT token signature is 'signature' encoded in base 64:
        assert signature == b"signature" 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:23,代碼來源:test_credentials.py

示例8: verify_token

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def verify_token(id_token, request, audience=None, certs_url=_GOOGLE_OAUTH2_CERTS_URL):
    """Verifies an ID token and returns the decoded token.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. If None
            then the audience is not verified.
        certs_url (str): The URL that specifies the certificates to use to
            verify the token. This URL should return JSON in the format of
            ``{'key id': 'x509 certificate'}``.

    Returns:
        Mapping[str, Any]: The decoded token.
    """
    certs = _fetch_certs(request, certs_url)

    return jwt.decode(id_token, certs=certs, audience=audience) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:21,代碼來源:id_token.py

示例9: verify_firebase_token

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def verify_firebase_token(id_token, request, audience=None):
    """Verifies an ID Token issued by Firebase Authentication.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your Firebase application ID. If None then the audience
            is not verified.

    Returns:
        Mapping[str, Any]: The decoded token.
    """
    return verify_token(
        id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL
    ) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:19,代碼來源:id_token.py

示例10: _check_adc

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def _check_adc():
  """Return whether the application default credential exists and is valid."""
  # google-auth wants to warn the user if no project is set, which makes sense
  # for cloud-only users, but not in our case. We temporarily chnage the logging
  # level here to silence.
  logger = _logging.getLogger()
  log_level = logger.level
  logger.setLevel(_logging.ERROR)
  try:
    creds, _ = _google_auth.default()
  except _google_auth.exceptions.DefaultCredentialsError:
    return False
  finally:
    logger.setLevel(log_level)
  transport = _auth_requests.Request()
  try:
    creds.refresh(transport)
  except Exception as e:  # pylint:disable=broad-except
    _logging.info('Failure refreshing credentials: %s', e)
  return creds.valid 
開發者ID:googlecolab,項目名稱:colabtools,代碼行數:22,代碼來源:auth.py

示例11: _fetch_certs

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def _fetch_certs(request, certs_url):
    """Fetches certificates.

    Google-style cerificate endpoints return JSON in the format of
    ``{'key id': 'x509 certificate'}``.

    Args:
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        certs_url (str): The certificate endpoint URL.

    Returns:
        Mapping[str, str]: A mapping of public key ID to x.509 certificate
            data.
    """
    response = request(certs_url, method='GET')

    if response.status != http_client.OK:
        raise exceptions.TransportError(
            'Could not fetch certificates at {}'.format(certs_url))

    return json.loads(response.data.decode('utf-8')) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:24,代碼來源:id_token.py

示例12: verify_token

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def verify_token(id_token, request, audience=None,
                 certs_url=_GOOGLE_OAUTH2_CERTS_URL):
    """Verifies an ID token and returns the decoded token.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. If None
            then the audience is not verified.
        certs_url (str): The URL that specifies the certificates to use to
            verify the token. This URL should return JSON in the format of
            ``{'key id': 'x509 certificate'}``.

    Returns:
        Mapping[str, Any]: The decoded token.
    """
    certs = _fetch_certs(request, certs_url)

    return jwt.decode(id_token, certs=certs, audience=audience) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:22,代碼來源:id_token.py

示例13: verify_oauth2_token

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def verify_oauth2_token(id_token, request, audience=None):
    """Verifies an ID Token issued by Google's OAuth 2.0 authorization server.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your application's OAuth 2.0 client ID. If None then the
            audience is not verified.

    Returns:
        Mapping[str, Any]: The decoded token.
    """
    return verify_token(
        id_token, request, audience=audience,
        certs_url=_GOOGLE_OAUTH2_CERTS_URL) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:19,代碼來源:id_token.py

示例14: verify_firebase_token

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import Request [as 別名]
def verify_firebase_token(id_token, request, audience=None):
    """Verifies an ID Token issued by Firebase Authentication.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your Firebase application ID. If None then the audience
            is not verified.

    Returns:
        Mapping[str, Any]: The decoded token.
    """
    return verify_token(
        id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:18,代碼來源:id_token.py


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