本文整理汇总了Python中oauth2client.client方法的典型用法代码示例。如果您正苦于以下问题:Python oauth2client.client方法的具体用法?Python oauth2client.client怎么用?Python oauth2client.client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client
的用法示例。
在下文中一共展示了oauth2client.client方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authorize
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def authorize(flags, scope, client_secrets_path, credentials_path):
"""Authorizes an HTTP object with the user's credentials.
Args:
flags: Command-line flags from argparse.ArgumentParser.parse_args().
scope: OAuth scope URL.
client_secret_path: Path to an existing client_secrets.json file.
credentials_path: Path where the user's credentials are stored; if
this file doesn't exist yet, the user will be taken through the
consent flow and then the credentials will be saved here.
"""
storage = oauth2client.file.Storage(credentials_path)
credentials = storage.get()
if not credentials or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(
client_secrets_path, scope=scope,
message=oauth2client.tools.message_if_missing(client_secrets_path))
credentials = oauth2client.tools.run_flow(flow, storage, flags)
return credentials.authorize(httplib2.Http())
示例2: _GetPersistentCredentials
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def _GetPersistentCredentials():
"""Read persistent credentials from ~/.config/earthengine.
Raises EEException with helpful explanation if credentials don't exist.
Returns:
OAuth2Credentials built from persistently stored refresh_token
"""
try:
tokens = json.load(open(oauth.get_credentials_path()))
refresh_token = tokens['refresh_token']
return oauth2client.client.OAuth2Credentials(
None, oauth.CLIENT_ID, oauth.CLIENT_SECRET, refresh_token,
None, 'https://accounts.google.com/o/oauth2/token', None)
except IOError:
raise EEException('Please authorize access to your Earth Engine account '
'by running\n\nearthengine authenticate\n\nin your '
'command line, and then retry.')
示例3: get_gmail_credentials
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def get_gmail_credentials(
scopes=[
'https://www.googleapis.com/auth/gmail.settings.basic',
'https://www.googleapis.com/auth/gmail.labels',
],
client_secret_path='client_secret.json',
application_name='gmail_yaml_filters',
):
credential_dir = os.path.join(os.path.expanduser('~'), '.credentials')
credential_path = os.path.join(credential_dir, application_name + '.json')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(client_secret_path, scopes)
flow.user_agent = application_name
flags_parser = argparse.ArgumentParser(parents=[oauth2client.tools.argparser])
credentials = oauth2client.tools.run_flow(flow, store, flags=flags_parser.parse_args([]))
print('Storing credentials to', credential_path, file=sys.stderr)
return credentials
示例4: with_scopes
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def with_scopes(credentials, scopes):
"""Scopes the credentials if necessary.
Args:
credentials (Union[
google.auth.credentials.Credentials,
oauth2client.client.Credentials]): The credentials to scope.
scopes (Sequence[str]): The list of scopes.
Returns:
Union[google.auth.credentials.Credentials,
oauth2client.client.Credentials]: The scoped credentials.
"""
if HAS_GOOGLE_AUTH and isinstance(
credentials, google.auth.credentials.Credentials):
return google.auth.credentials.with_scopes_if_required(
credentials, scopes)
else:
try:
if credentials.create_scoped_required():
return credentials.create_scoped(scopes)
else:
return credentials
except AttributeError:
return credentials
示例5: __init__
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def __init__(self, http, service_account_email, scopes, project='-'):
"""
Args:
http: An httplib2.Http object that is authorized by another
oauth2client.client.OAuth2Credentials with credentials that have the
service account actor role on the service_account_email.
service_account_email: The email address of the service account for which
to obtain an access token.
scopes: The desired scopes for the token.
project: The cloud project to which service_account_email belongs. The
default of '-' makes the IAM API figure it out for us.
"""
super(DelegateServiceAccountCredentials, self).__init__(None)
self._service_account_email = service_account_email
self._scopes = util.scopes_to_string(scopes)
self._http = http
self._name = 'projects/%s/serviceAccounts/%s' % (
project, service_account_email)
示例6: __init__
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def __init__(self, http, service_account_email, scopes, project='-'):
"""
Args:
http: An httplib2.Http object that is authorized by another
oauth2client.client.OAuth2Credentials with credentials that have the
service account token creator role on the service_account_email.
service_account_email: The email address of the service account for which
to obtain an access token.
scopes: The desired scopes for the token.
project: The cloud project to which service_account_email belongs. The
default of '-' makes the IAM API figure it out for us.
"""
super(DelegateServiceAccountCredentials, self).__init__(
None, None, None, None, None, None, None)
self._http = http
self._sa_email = service_account_email
self._scopes = self._canonicalize_scopes(scopes)
self._project = project
self.token_expiry = None
self.access_token = None
示例7: GetCredentials
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
credentials_filename=None,
api_key=None, # pylint: disable=unused-argument
client=None, # pylint: disable=unused-argument
oauth2client_args=None,
**kwds):
"""Attempt to get credentials, using an oauth dance as the last resort."""
scopes = util.NormalizeScopes(scopes)
client_info = {
'client_id': client_id,
'client_secret': client_secret,
'scope': ' '.join(sorted(scopes)),
'user_agent': user_agent or '%s-generated/0.1' % package_name,
}
for method in _CREDENTIALS_METHODS:
credentials = method(client_info, **kwds)
if credentials is not None:
return credentials
credentials_filename = credentials_filename or os.path.expanduser(
'~/.apitools.token')
credentials = CredentialsFromFile(credentials_filename, client_info,
oauth2client_args=oauth2client_args)
if credentials is not None:
return credentials
raise exceptions.CredentialsError('Could not create valid credentials')
示例8: ServiceAccountCredentialsFromP12File
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def ServiceAccountCredentialsFromP12File(
service_account_name, private_key_filename, scopes, user_agent):
"""Create a new credential from the named .p12 keyfile."""
private_key_filename = os.path.expanduser(private_key_filename)
scopes = util.NormalizeScopes(scopes)
if oauth2client.__version__ > '1.5.2':
# oauth2client >= 2.0.0
credentials = (
service_account.ServiceAccountCredentials.from_p12_keyfile(
service_account_name, private_key_filename, scopes=scopes))
if credentials is not None:
credentials.user_agent = user_agent
return credentials
else:
# oauth2client < 2.0.0
with open(private_key_filename, 'rb') as key_file:
return oauth2client.client.SignedJwtAssertionCredentials(
service_account_name, key_file.read(), scopes,
user_agent=user_agent)
示例9: from_json
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def from_json(cls, json_data):
data = json.loads(json_data)
kwargs = {}
if 'cache_filename' in data.get('kwargs', []):
kwargs['cache_filename'] = data['kwargs']['cache_filename']
# Newer versions of GceAssertionCredentials don't have a "scope"
# attribute.
scope_list = None
if 'scope' in data:
scope_list = [data['scope']]
credentials = GceAssertionCredentials(scopes=scope_list, **kwargs)
if 'access_token' in data:
credentials.access_token = data['access_token']
if 'token_expiry' in data:
credentials.token_expiry = datetime.datetime.strptime(
data['token_expiry'], oauth2client.client.EXPIRY_FORMAT)
if 'invalid' in data:
credentials.invalid = data['invalid']
return credentials
示例10: GetUserinfo
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def GetUserinfo(credentials, http=None): # pylint: disable=invalid-name
"""Get the userinfo associated with the given credentials.
This is dependent on the token having either the userinfo.email or
userinfo.profile scope for the given token.
Args:
credentials: (oauth2client.client.Credentials) incoming credentials
http: (httplib2.Http, optional) http instance to use
Returns:
The email address for this token, or None if the required scopes
aren't available.
"""
http = http or httplib2.Http()
url = _GetUserinfoUrl(credentials)
# We ignore communication woes here (i.e. SSL errors, socket
# timeout), as handling these should be done in a common location.
response, content = http.request(url)
if response.status == http_client.BAD_REQUEST:
credentials.refresh(http)
url = _GetUserinfoUrl(credentials)
response, content = http.request(url)
return json.loads(content or '{}') # Save ourselves from an empty reply.
示例11: to_python
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
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))
示例12: credentials_from_code
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def credentials_from_code(code):
""" Exchange code for client secrets """
return oauth2client.client.credentials_from_clientsecrets_and_code(
_CLIENT_SECRETS, SCOPES, code)
示例13: ServiceAccountCredentials
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def ServiceAccountCredentials(email, key_file=None, key_data=None):
"""Configure OAuth2 credentials for a Google Service Account.
Args:
email: The email address of the account for which to configure credentials.
key_file: The path to a file containing the private key associated with
the service account. PEM files are supported for oauth2client v1 and
JSON files are supported for oauth2client v2+.
key_data: Raw key data to use, if key_file is not specified.
Returns:
An OAuth2 credentials object.
Raises:
NotImplementedError: Occurs if using oauth2client v2+ and a PEM formatted
credentials key file.
"""
try:
# oauth2client v2+ and JSON key
sa_creds = oauth2client.service_account.ServiceAccountCredentials
credentials = sa_creds.from_json_keyfile_name(key_file, oauth.SCOPE)
except ValueError:
# oauth2client v2+ and PEM key
raise NotImplementedError(
'When using oauth2client version 2 or later, you must use a JSON '
'formatted key file (instead of a p12 or PEM formatted file). See the '
'following page for information on creating a JSON formatted file:\n'
'https://developers.google.com/api-client-library/python/auth/web-app')
except AttributeError:
# oauth2client v1 (i.e. does not have a ServiceAccountCredentials)
if key_file:
with open(key_file, 'rb') as key_file:
key_data = key_file.read()
credentials = oauth2client.client.SignedJwtAssertionCredentials(
email, key_data, oauth.SCOPE)
return credentials
示例14: to_python
# 需要导入模块: import oauth2client [as 别名]
# 或者: from oauth2client import client [as 别名]
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(smart_bytes(value)))