Remove httplib2 imports from non-transport modules.

Now all usage of httplib2 is concentrated in tests and
in the oauth2client.transport module. This does not yet
cover all behavior that implicitly relies on httplib2
in these modules, so there is still work to be done.
This commit is contained in:
Danny Hermes
2016-07-29 11:24:17 -07:00
parent eb019c2dad
commit 80fff4bda1
8 changed files with 31 additions and 17 deletions

View File

@@ -20,7 +20,6 @@ See https://cloud.google.com/compute/docs/metadata
import datetime import datetime
import json import json
import httplib2
from six.moves import http_client from six.moves import http_client
from six.moves.urllib import parse as urlparse from six.moves.urllib import parse as urlparse
@@ -51,7 +50,8 @@ def get(http_request, path, root=METADATA_ROOT, recursive=None):
A dictionary if the metadata server returns JSON, otherwise a string. A dictionary if the metadata server returns JSON, otherwise a string.
Raises: Raises:
httplib2.Httplib2Error if an error corrured while retrieving metadata. http_client.HTTPException if an error corrured while
retrieving metadata.
""" """
url = urlparse.urljoin(root, path) url = urlparse.urljoin(root, path)
url = util._add_query_parameter(url, 'recursive', recursive) url = util._add_query_parameter(url, 'recursive', recursive)
@@ -68,7 +68,7 @@ def get(http_request, path, root=METADATA_ROOT, recursive=None):
else: else:
return decoded return decoded
else: else:
raise httplib2.HttpLib2Error( raise http_client.HTTPException(
'Failed to retrieve {0} from the Google Compute Engine' 'Failed to retrieve {0} from the Google Compute Engine'
'metadata service. Response:\n{1}'.format(url, response)) 'metadata service. Response:\n{1}'.format(url, response))

View File

@@ -29,12 +29,12 @@ from google.appengine.api import memcache
from google.appengine.api import users from google.appengine.api import users
from google.appengine.ext import db from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import login_required
import httplib2
import webapp2 as webapp import webapp2 as webapp
import oauth2client import oauth2client
from oauth2client import client from oauth2client import client
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import transport
from oauth2client import util from oauth2client import util
from oauth2client.contrib import xsrfutil from oauth2client.contrib import xsrfutil
@@ -742,7 +742,8 @@ class OAuth2Decorator(object):
*args: Positional arguments passed to httplib2.Http constructor. *args: Positional arguments passed to httplib2.Http constructor.
**kwargs: Positional arguments passed to httplib2.Http constructor. **kwargs: Positional arguments passed to httplib2.Http constructor.
""" """
return self.credentials.authorize(httplib2.Http(*args, **kwargs)) return self.credentials.authorize(
transport.get_http_object(*args, **kwargs))
@property @property
def callback_path(self): def callback_path(self):

View File

@@ -228,10 +228,10 @@ import importlib
import django.conf import django.conf
from django.core import exceptions from django.core import exceptions
from django.core import urlresolvers from django.core import urlresolvers
import httplib2
from six.moves.urllib import parse from six.moves.urllib import parse
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import transport
from oauth2client.contrib import dictionary_storage from oauth2client.contrib import dictionary_storage
from oauth2client.contrib.django_util import storage from oauth2client.contrib.django_util import storage
@@ -470,8 +470,7 @@ class UserOAuth2(object):
@property @property
def http(self): def http(self):
"""Helper method to create an HTTP client authorized with OAuth2 """Helper: create HTTP client authorized with OAuth2 credentials."""
credentials."""
if self.has_credentials(): if self.has_credentials():
return self.credentials.authorize(httplib2.Http()) return self.credentials.authorize(transport.get_http_object())
return None return None

View File

@@ -179,11 +179,11 @@ try:
except ImportError: # pragma: NO COVER except ImportError: # pragma: NO COVER
raise ImportError('The flask utilities require flask 0.9 or newer.') raise ImportError('The flask utilities require flask 0.9 or newer.')
import httplib2
import six.moves.http_client as httplib import six.moves.http_client as httplib
from oauth2client import client from oauth2client import client
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import transport
from oauth2client.contrib import dictionary_storage from oauth2client.contrib import dictionary_storage
@@ -553,4 +553,5 @@ class UserOAuth2(object):
""" """
if not self.credentials: if not self.credentials:
raise ValueError('No credentials available.') raise ValueError('No credentials available.')
return self.credentials.authorize(httplib2.Http(*args, **kwargs)) return self.credentials.authorize(
transport.get_http_object(*args, **kwargs))

View File

@@ -20,7 +20,7 @@ Utilities for making it easier to use OAuth 2.0 on Google Compute Engine.
import logging import logging
import warnings import warnings
import httplib2 from six.moves import http_client
from oauth2client import client from oauth2client import client
from oauth2client.contrib import _metadata from oauth2client.contrib import _metadata
@@ -134,8 +134,8 @@ class AppAssertionCredentials(client.AssertionCredentials):
self._retrieve_info(http_request) self._retrieve_info(http_request)
self.access_token, self.token_expiry = _metadata.get_token( self.access_token, self.token_expiry = _metadata.get_token(
http_request, service_account=self.service_account_email) http_request, service_account=self.service_account_email)
except httplib2.HttpLib2Error as e: except http_client.HTTPException as err:
raise client.HttpAccessTokenRefreshError(str(e)) raise client.HttpAccessTokenRefreshError(str(err))
@property @property
def serialization_data(self): def serialization_data(self):

View File

@@ -58,13 +58,19 @@ def get_cached_http():
return _CACHED_HTTP return _CACHED_HTTP
def get_http_object(): def get_http_object(*args, **kwargs):
"""Return a new HTTP object. """Return a new HTTP object.
Args:
*args: tuple, The positional arguments to be passed when
contructing a new HTTP object.
**kwargs: dict, The keyword arguments to be passed when
contructing a new HTTP object.
Returns: Returns:
httplib2.Http, an HTTP object. httplib2.Http, an HTTP object.
""" """
return httplib2.Http() return httplib2.Http(*args, **kwargs)
def _initialize_headers(headers): def _initialize_headers(headers):

View File

@@ -62,7 +62,7 @@ class TestMetadata(unittest2.TestCase):
def test_get_failure(self): def test_get_failure(self):
http_request = request_mock( http_request = request_mock(
http_client.NOT_FOUND, 'text/html', '<p>Error</p>') http_client.NOT_FOUND, 'text/html', '<p>Error</p>')
with self.assertRaises(httplib2.HttpLib2Error): with self.assertRaises(http_client.HTTPException):
_metadata.get(http_request, PATH) _metadata.get(http_request, PATH)
http_request.assert_called_once_with(EXPECTED_URL, **EXPECTED_KWARGS) http_request.assert_called_once_with(EXPECTED_URL, **EXPECTED_KWARGS)

View File

@@ -52,6 +52,13 @@ class Test_get_http_object(unittest2.TestCase):
def test_it(self, http_klass): def test_it(self, http_klass):
result = transport.get_http_object() result = transport.get_http_object()
self.assertEqual(result, http_klass.return_value) self.assertEqual(result, http_klass.return_value)
http_klass.assert_called_once_with()
@mock.patch.object(httplib2, 'Http', return_value=object())
def test_with_args(self, http_klass):
result = transport.get_http_object(1, 2, foo='bar')
self.assertEqual(result, http_klass.return_value)
http_klass.assert_called_once_with(1, 2, foo='bar')
class Test__initialize_headers(unittest2.TestCase): class Test__initialize_headers(unittest2.TestCase):