def create(apiName, apiVersion):
credentials = GoogleCredentials.get_application_default()
http = credentials.authorize(httplib2.Http())
if credentials.access_token_expired:
credentials.refresh(http)
return discovery.build(apiName, apiVersion, http)
python类Http()的实例源码
def get_authenticated_service(self):
""" Create youtube oauth2 connection """
credentials = AccessTokenCredentials(
access_token=self.get_auth_code(),
user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
)
return build(
'youtube', 'v3', http=credentials.authorize(httplib2.Http())
)
def request_master(url,data):
global G_masterip
header = {'Content-Type':'application/x-www-form-urlencoded'}
http = Http()
[resp,content] = http.request("http://"+G_masterip+url,"POST",urlencode(data),headers = header)
logger.info("response from master:"+content.decode('utf-8'))
# The class is to collect data of containers on each worker
def request_master(url,data):
global G_masterip
#logger.info("master_ip:"+str(G_masterip))
header = {'Content-Type':'application/x-www-form-urlencoded'}
http = Http()
for masterip in G_masterips:
[resp,content] = http.request("http://"+masterip+url,"POST",urlencode(data),headers = header)
logger.info("response from master:"+content.decode('utf-8'))
def oauth2callback():
flow = oauth2client.client.flow_from_clientsecrets(
'client_secrets_oauth.json',
scope=[
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'],
redirect_uri=flask.url_for('oauth2callback', _external=True))
if 'code' not in flask.request.args:
auth_uri = flow.step1_get_authorize_url()
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
credentials = flow.step2_exchange(auth_code)
flask.session['credentials'] = credentials.to_json()
# use token to get user profile from google oauth api
http_auth = credentials.authorize(httplib2.Http())
userinfo_client = apiclient.discovery.build('oauth2', 'v2', http_auth)
user = userinfo_client.userinfo().v2().me().get().execute()
# TODO only allow columbia.edu emails
# if 'columbia.edu' not in user['email']:
# return flask.redirect(flask.url_for('bademail'))
um = users_model.Users()
flask.session['google_user'] = user
flask.session['id'] = um.get_or_create_user(user)
# now add is_student and is_teacher to flask.session
im = index_model.Index(flask.session['id'])
flask.session['is_student'] = True if im.is_student() else False
flask.session['is_teacher'] = True if im.is_teacher() else False
redirect = flask.session['redirect']
flask.session.pop('redirect', None)
return flask.redirect(redirect)
def create_service():
credentials = appengine.AppAssertionCredentials(SCOPE)
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
return discovery.build('content', 'v1', http=http,
discoveryServiceUrl=DISCOVERY_URL)
def create_pubsub_client(http=None):
credentials = oauth2client.GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
credentials = credentials.create_scoped(PUBSUB_SCOPES)
if not http:
http = httplib2.Http()
credentials.authorize(http)
return discovery.build('pubsub', 'v1', http=http)
def create_datastore_client(http=None):
credentials = oauth2client.GoogleCredentials.get_application_default()
if not http:
http = httplib2.Http()
credentials.authorize(http)
return datastore.Client(credentials=credentials)
def create_datastore_client(http=None):
credentials = oauth2client.GoogleCredentials.get_application_default()
if not http:
http = httplib2.Http()
credentials.authorize(http)
return datastore.Client(credentials=credentials)
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and authorizes it.
Authorizes it for the set of credentials, usually by replacing
http.request() with a method that adds in the appropriate headers and
then delegates to the original Http.request() method.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
self._refresh(http.request)
def revoke(self, http):
"""Revokes a refresh_token and makes the credentials void.
Args:
http: httplib2.Http, an http object to be used to make the revoke
request.
"""
self._revoke(http.request)
def retrieve_scopes(self, http):
"""Retrieves the canonical list of scopes for this access token.
Gets the scopes from the OAuth2 provider.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
Returns:
A set of strings containing the canonical list of scopes.
"""
self._retrieve_scopes(http.request)
return self.scopes
def get_access_token(self, http=None):
"""Return the access token and its expiration information.
If the token does not exist, get one.
If the token expired, refresh it.
"""
if not self.access_token or self.access_token_expired:
if not http:
http = httplib2.Http()
self.refresh(http)
return AccessTokenInfo(access_token=self.access_token,
expires_in=self._expires_in())
def _refresh(self, http_request):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make the
refresh request.
Raises:
HttpAccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http_request)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token and
not new_cred.access_token_expired):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http_request)
finally:
self.store.release_lock()
def _revoke(self, http_request):
"""Revokes this credential and deletes the stored copy (if it exists).
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make the
revoke request.
"""
self._do_revoke(http_request, self.refresh_token or self.access_token)
def _do_revoke(self, http_request, token):
"""Revokes this credential and deletes the stored copy (if it exists).
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make the
refresh request.
token: A string used as the token to be revoked. Can be either an
access_token or refresh_token.
Raises:
TokenRevokeError: If the revoke request does not return with a
200 OK.
"""
logger.info('Revoking token')
query_params = {'token': token}
token_revoke_uri = _update_query_params(self.revoke_uri, query_params)
resp, content = http_request(token_revoke_uri)
if resp.status == http_client.OK:
self.invalid = True
else:
error_msg = 'Invalid response %s.' % resp.status
try:
d = json.loads(_from_bytes(content))
if 'error' in d:
error_msg = d['error']
except (TypeError, ValueError):
pass
raise TokenRevokeError(error_msg)
if self.store:
self.store.delete()
def _retrieve_scopes(self, http_request):
"""Retrieves the list of authorized scopes from the OAuth2 provider.
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make the
revoke request.
"""
self._do_retrieve_scopes(http_request, self.access_token)
def _do_retrieve_scopes(self, http_request, token):
"""Retrieves the list of authorized scopes from the OAuth2 provider.
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make the
refresh request.
token: A string used as the token to identify the credentials to
the provider.
Raises:
Error: When refresh fails, indicating the the access token is
invalid.
"""
logger.info('Refreshing scopes')
query_params = {'access_token': token, 'fields': 'scope'}
token_info_uri = _update_query_params(self.token_info_uri,
query_params)
resp, content = http_request(token_info_uri)
content = _from_bytes(content)
if resp.status == http_client.OK:
d = json.loads(content)
self.scopes = set(util.string_to_scopes(d.get('scope', '')))
else:
error_msg = 'Invalid response %s.' % (resp.status,)
try:
d = json.loads(content)
if 'error_description' in d:
error_msg = d['error_description']
except (TypeError, ValueError):
pass
raise Error(error_msg)