本文整理汇总了Python中google.oauth2.credentials.Credentials方法的典型用法代码示例。如果您正苦于以下问题:Python credentials.Credentials方法的具体用法?Python credentials.Credentials怎么用?Python credentials.Credentials使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.oauth2.credentials
的用法示例。
在下文中一共展示了credentials.Credentials方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def get_credentials(self, scopes):
"""Get the user credentials for deployment.
Args:
scopes: List[str], a list of the required scopes for this credential.
Returns:
A credentials.Credentials object for the authenticated user.
"""
if os.path.isfile(self._config.local_credentials_file_path):
creds = self._get_credentials_from_file(scopes)
if creds:
return creds
else:
logging.info(
'Credentials were not found locally, requesting new credentials.')
return self._request_new_credentials(scopes)
示例2: _get_credentials_from_file
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def _get_credentials_from_file(self, scopes):
"""Gets the OAuth2 credential from file if it contains the scopes provided.
Args:
scopes: List[str], a list of the required scopes for this credential.
Returns:
A credentials.Credentials object for the authenticated user or None if the
stored credential does not contain the provided scopes.
"""
with open(
self._config.local_credentials_file_path, 'r') as json_file:
data = json.load(json_file)
if data['scopes'] and set(scopes).issubset(set(data['scopes'])):
logging.info('The requested scopes are authorized by this credential.')
return credentials.Credentials.from_authorized_user_info(data, scopes)
else:
logging.info(
'The requested scopes are not authorized by this credential. '
'Requesting new credentials...')
return None
示例3: put_user_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def put_user_credentials(
self, user_name: str, creds: Credentials) -> None:
"""Stores OAuth2 credentials for a user.
Args:
user_name (str): The identifier for the associated user.
creds (Credentials): The OAuth2 credentials obtained for the user.
"""
key = self.datastore_client.key('RefreshToken', user_name)
entity = datastore.Entity(key)
entity.update({
'credentials': {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes,
},
'timestamp': time.time()
})
self.datastore_client.put(entity)
示例4: test_from_authorized_user_file
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def test_from_authorized_user_file(self):
info = AUTH_USER_INFO.copy()
creds = credentials.Credentials.from_authorized_user_file(AUTH_USER_JSON_FILE)
assert creds.client_secret == info["client_secret"]
assert creds.client_id == info["client_id"]
assert creds.refresh_token == info["refresh_token"]
assert creds.token_uri == credentials._GOOGLE_OAUTH2_TOKEN_ENDPOINT
assert creds.scopes is None
scopes = ["email", "profile"]
creds = credentials.Credentials.from_authorized_user_file(
AUTH_USER_JSON_FILE, scopes
)
assert creds.client_secret == info["client_secret"]
assert creds.client_id == info["client_id"]
assert creds.refresh_token == info["refresh_token"]
assert creds.token_uri == credentials._GOOGLE_OAUTH2_TOKEN_ENDPOINT
assert creds.scopes == scopes
示例5: test_to_json
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def test_to_json(self):
info = AUTH_USER_INFO.copy()
creds = credentials.Credentials.from_authorized_user_info(info)
# Test with no `strip` arg
json_output = creds.to_json()
json_asdict = json.loads(json_output)
assert json_asdict.get("token") == creds.token
assert json_asdict.get("refresh_token") == creds.refresh_token
assert json_asdict.get("token_uri") == creds.token_uri
assert json_asdict.get("client_id") == creds.client_id
assert json_asdict.get("scopes") == creds.scopes
assert json_asdict.get("client_secret") == creds.client_secret
# Test with a `strip` arg
json_output = creds.to_json(strip=["client_secret"])
json_asdict = json.loads(json_output)
assert json_asdict.get("token") == creds.token
assert json_asdict.get("refresh_token") == creds.refresh_token
assert json_asdict.get("token_uri") == creds.token_uri
assert json_asdict.get("client_id") == creds.client_id
assert json_asdict.get("scopes") == creds.scopes
assert json_asdict.get("client_secret") is None
示例6: create_default_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def create_default_credentials() -> credentials.Credentials:
"""Retrieves google application default credentials for authentication.
Uses subprocess to call gcloud auth application-default login. User must
have gcloud installed.
Returns:
Credentials Object
"""
# We can not use "gcloud auth application-default login" here because
# we use "gcloud app deploy" to deploy a Django app to app-engine. It
# requires "gcloud auth login".
command = ['gcloud', 'auth', 'login', '-q']
subprocess.check_call(command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return AuthClient.get_default_credentials()
示例7: get_default_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def get_default_credentials() -> Optional[credentials.Credentials]:
"""Get the default credentials object created by "gcloud auth login".
Returns:
The credentials object if it is valid and not expired. Otherwise
None.
"""
credentials_path = AuthClient._get_active_account_adc_path()
try:
creds = credentials.Credentials.from_authorized_user_file(
credentials_path)
if creds.expired:
return None
else:
return creds
# If credentials file not found or it is invalid.
except (AttributeError, ValueError, FileNotFoundError):
return None
示例8: from_bytes
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def from_bytes(self, data):
"""Deserialize a credential object from bytes.
Args:
data (bytes): serialized credential object.
Raises:
TypeError: if the data is not in bytes.
"""
if not isinstance(data, bytes):
raise TypeError('Data needs to be bytes.')
try:
token_dict = json.loads(data.decode('utf-8'))
except ValueError:
raise TypeError('Unable to parse the byte string.')
self._credential = credentials.Credentials(
token=token_dict.get('token'),
refresh_token=token_dict.get('_refresh_token'),
id_token=token_dict.get('_id_token'),
token_uri=token_dict.get('_token_uri'),
client_id=token_dict.get('_client_id'),
client_secret=token_dict.get('_client_secret')
)
示例9: _verify_credential
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def _verify_credential(self, credential):
assert credential.client_id == 'mock.apps.googleusercontent.com'
assert credential.client_secret == 'mock-secret'
assert credential.refresh_token == 'mock-refresh-token'
g_credential = credential.get_credential()
assert isinstance(g_credential, gcredentials.Credentials)
assert g_credential.token is None
check_scopes(g_credential)
mock_response = {
'access_token': 'mock_access_token',
'expires_in': 3600
}
credentials._request = testutils.MockRequest(200, json.dumps(mock_response))
access_token = credential.get_access_token()
assert access_token.access_token == 'mock_access_token'
assert isinstance(access_token.expiry, datetime.datetime)
示例10: token
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def token(self, token):
"""Read access token and process it."""
self.oauth2.fetch_token(self.user_data['token_uri'], client_secret=self.user_data['client_secret'], code=token)
# create credentials
credentials = Credentials(
self.oauth2.token['access_token'],
refresh_token=self.oauth2.token.get('refresh_token'),
token_uri=self.user_data['token_uri'],
client_id=self.user_data['client_id'],
client_secret=self.user_data['client_secret'],
scopes=self.oauth2.scope
)
# write credentials json file
with self.cred_file.open('w') as json_file:
json_file.write(json.dumps({
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes,
}))
sys.exit(0)
示例11: get_user_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def get_user_credentials(self, user_name: str) -> Union[Credentials, None]:
"""Retrieves stored OAuth2 credentials for a user.
Args:
user_name (str): The identifier for the user.
Returns:
A Credentials object, or None if the user has not authorized the bot.
"""
key = self.datastore_client.key('RefreshToken', user_name)
entity = self.datastore_client.get(key)
if entity is None or 'credentials' not in entity:
return None
return Credentials(**entity['credentials'])
示例12: make_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def make_credentials(
self,
source_credentials=SOURCE_CREDENTIALS,
lifetime=LIFETIME,
target_principal=TARGET_PRINCIPAL,
):
return Credentials(
source_credentials=source_credentials,
target_principal=target_principal,
target_scopes=self.TARGET_SCOPES,
delegates=self.DELEGATES,
lifetime=lifetime,
)
示例13: test_refresh_source_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def test_refresh_source_credentials(self, time_skew):
credentials = self.make_credentials(lifetime=None)
# Source credentials is refreshed only if it is expired within
# _helpers.CLOCK_SKEW from now. We add a time_skew to the expiry, so
# source credentials is refreshed only if time_skew <= 0.
credentials._source_credentials.expiry = (
_helpers.utcnow()
+ _helpers.CLOCK_SKEW
+ datetime.timedelta(seconds=time_skew)
)
credentials._source_credentials.token = "Token"
with mock.patch(
"google.oauth2.service_account.Credentials.refresh", autospec=True
) as source_cred_refresh:
expire_time = (
_helpers.utcnow().replace(microsecond=0)
+ datetime.timedelta(seconds=500)
).isoformat("T") + "Z"
response_body = {"accessToken": "token", "expireTime": expire_time}
request = self.make_request(
data=json.dumps(response_body), status=http_client.OK
)
credentials.refresh(request)
assert credentials.valid
assert not credentials.expired
# Source credentials is refreshed only if it is expired within
# _helpers.CLOCK_SKEW
if time_skew > 0:
source_cred_refresh.assert_not_called()
else:
source_cred_refresh.assert_called_once()
示例14: test_signer
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def test_signer(self):
credentials = self.make_credentials()
assert isinstance(credentials.signer, impersonated_credentials.Credentials)
示例15: make_credentials
# 需要导入模块: from google.oauth2 import credentials [as 别名]
# 或者: from google.oauth2.credentials import Credentials [as 别名]
def make_credentials(cls):
return credentials.Credentials(
token=None,
refresh_token=cls.REFRESH_TOKEN,
token_uri=cls.TOKEN_URI,
client_id=cls.CLIENT_ID,
client_secret=cls.CLIENT_SECRET,
)