Use six.string_types instead of basestring

basestring only exists in Python 2. Use six.string_types to make code
Python 3 compatible. See http://pythonhosted.org/six/#six.string_types

Part of blueprint keystone-py3kcompat

Change-Id: I5022259cfd648ba2680aabbb0fbc403f10c5dc7e
This commit is contained in:
Eric Guo 2014-01-17 21:34:39 +08:00
parent c8099159f9
commit 5555ded3d4
13 changed files with 40 additions and 17 deletions

View File

@ -22,6 +22,8 @@ import urllib
import urlparse import urlparse
import uuid import uuid
import six
from keystone.common import controller from keystone.common import controller
from keystone.common import dependency from keystone.common import dependency
from keystone import config from keystone import config
@ -828,7 +830,7 @@ class RoleAssignmentV3(controller.V3Controller):
""" """
if (isinstance(filter_value, basestring) and if (isinstance(filter_value, six.string_types) and
filter_value == '0'): filter_value == '0'):
val = False val = False
else: else:

View File

@ -14,6 +14,8 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import six
from keystone import exception from keystone import exception
@ -50,7 +52,8 @@ def check_enabled(property_name, enabled):
def check_name(property_name, name, min_length=1, max_length=64): def check_name(property_name, name, min_length=1, max_length=64):
check_type('%s name' % property_name, name, basestring, 'str or unicode') check_type('%s name' % property_name, name, six.string_types,
'str or unicode')
name = name.strip() name = name.strip()
check_length('%s name' % property_name, name, check_length('%s name' % property_name, name,
min_length=min_length, max_length=max_length) min_length=min_length, max_length=max_length)

View File

@ -18,6 +18,8 @@ import collections
import functools import functools
import uuid import uuid
import six
from keystone.common import dependency from keystone.common import dependency
from keystone.common import wsgi from keystone.common import wsgi
from keystone import config from keystone import config
@ -317,7 +319,7 @@ class V3Controller(wsgi.Application):
""" """
if type(ref_attr) is bool: if type(ref_attr) is bool:
if (isinstance(val_attr, basestring) and if (isinstance(val_attr, six.string_types) and
val_attr == '0'): val_attr == '0'):
val = False val = False
else: else:

View File

@ -25,6 +25,8 @@ by convention, with a few hardcoded exceptions.
from lxml import etree from lxml import etree
import re import re
import six
DOCTYPE = '<?xml version="1.0" encoding="UTF-8"?>' DOCTYPE = '<?xml version="1.0" encoding="UTF-8"?>'
XMLNS = 'http://docs.openstack.org/identity/api/v2.0' XMLNS = 'http://docs.openstack.org/identity/api/v2.0'
@ -313,7 +315,7 @@ class XmlSerializer(object):
self.populate_element(child, item) self.populate_element(child, item)
element.append(child) element.append(child)
elif isinstance(value, basestring): elif isinstance(value, six.string_types):
element.text = unicode(value) element.text = unicode(value)
def _populate_sequence(self, element, l): def _populate_sequence(self, element, l):
@ -339,7 +341,7 @@ class XmlSerializer(object):
self._populate_list(element, k, v) self._populate_list(element, k, v)
elif isinstance(v, bool): elif isinstance(v, bool):
self._populate_bool(element, k, v) self._populate_bool(element, k, v)
elif isinstance(v, basestring): elif isinstance(v, six.string_types):
self._populate_str(element, k, v) self._populate_str(element, k, v)
elif type(v) in [int, float, long, complex]: elif type(v) in [int, float, long, complex]:
self._populate_number(element, k, v) self._populate_number(element, k, v)

View File

@ -16,6 +16,8 @@
import json import json
import six
from sqlalchemy import MetaData, Table from sqlalchemy import MetaData, Table
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
@ -27,7 +29,8 @@ def is_enabled(enabled):
# no explicit value means enabled # no explicit value means enabled
if enabled is True or enabled is None: if enabled is True or enabled is None:
return True return True
if isinstance(enabled, basestring) and enabled.lower() in DISABLED_VALUES: if (isinstance(enabled, six.string_types)
and enabled.lower() in DISABLED_VALUES):
return False return False
return bool(enabled) return bool(enabled)

View File

@ -26,6 +26,7 @@ import os
import pwd import pwd
import passlib.hash import passlib.hash
import six
from keystone.common import config from keystone.common import config
from keystone.common import environment from keystone.common import environment
@ -330,7 +331,7 @@ def get_unix_user(user=None):
:return: tuple of (uid, name) :return: tuple of (uid, name)
''' '''
if isinstance(user, basestring): if isinstance(user, six.string_types):
try: try:
user_info = pwd.getpwnam(user) user_info = pwd.getpwnam(user)
except KeyError: except KeyError:
@ -386,7 +387,7 @@ def get_unix_group(group=None):
:return: tuple of (gid, name) :return: tuple of (gid, name)
''' '''
if isinstance(group, basestring): if isinstance(group, six.string_types):
try: try:
group_info = grp.getgrnam(group) group_info = grp.getgrnam(group)
except KeyError: except KeyError:

View File

@ -231,7 +231,7 @@ class Application(BaseApplication):
if result is None: if result is None:
return render_response(status=(204, 'No Content')) return render_response(status=(204, 'No Content'))
elif isinstance(result, basestring): elif isinstance(result, six.string_types):
return result return result
elif isinstance(result, webob.Response): elif isinstance(result, webob.Response):
return result return result

View File

@ -16,6 +16,8 @@
"""oAuthlib request validator.""" """oAuthlib request validator."""
import six
from keystone.common import dependency from keystone.common import dependency
from keystone.contrib.oauth1 import core as oauth1 from keystone.contrib.oauth1 import core as oauth1
from keystone import exception from keystone import exception
@ -151,7 +153,7 @@ class OAuthValidator(oauth1.RequestValidator):
def verify_request_token(self, token, request): def verify_request_token(self, token, request):
# there aren't strong expectations on the request token format # there aren't strong expectations on the request token format
return isinstance(token, basestring) return isinstance(token, six.string_types)
def verify_realms(self, token, realms, request): def verify_realms(self, token, realms, request):
return True return True

View File

@ -28,6 +28,7 @@ import warnings
import fixtures import fixtures
import logging import logging
from paste import deploy from paste import deploy
import six
import testtools import testtools
from testtools import testcase from testtools import testcase
@ -471,7 +472,7 @@ class TestCase(testtools.TestCase):
try: try:
callable_obj(*args, **kwargs) callable_obj(*args, **kwargs)
except expected_exception as exc_value: except expected_exception as exc_value:
if isinstance(expected_regexp, basestring): if isinstance(expected_regexp, six.string_types):
expected_regexp = re.compile(expected_regexp) expected_regexp = re.compile(expected_regexp)
if isinstance(exc_value.args[0], gettextutils.Message): if isinstance(exc_value.args[0], gettextutils.Message):

View File

@ -18,6 +18,7 @@ import datetime
import uuid import uuid
from lxml import etree from lxml import etree
import six
from keystone import auth from keystone import auth
from keystone.common import cache from keystone.common import cache
@ -250,7 +251,7 @@ class RestfulTestCase(rest.RestfulTestCase):
ref['impersonation'] = impersonation or False ref['impersonation'] = impersonation or False
ref['project_id'] = project_id ref['project_id'] = project_id
if isinstance(expires, basestring): if isinstance(expires, six.string_types):
ref['expires_at'] = expires ref['expires_at'] = expires
elif isinstance(expires, dict): elif isinstance(expires, dict):
ref['expires_at'] = timeutils.strtime( ref['expires_at'] = timeutils.strtime(

View File

@ -18,6 +18,8 @@
from __future__ import absolute_import from __future__ import absolute_import
import copy import copy
import six
from keystone.common import kvs from keystone.common import kvs
from keystone import config from keystone import config
from keystone import exception from keystone import exception
@ -192,7 +194,7 @@ class Token(token.Driver):
current_time = self._get_current_time() current_time = self._get_current_time()
expires = data['expires'] expires = data['expires']
if isinstance(expires, basestring): if isinstance(expires, six.string_types):
expires = timeutils.parse_isotime(expires) expires = timeutils.parse_isotime(expires)
expires = timeutils.normalize_time(expires) expires = timeutils.normalize_time(expires)

View File

@ -17,6 +17,8 @@
import json import json
import sys import sys
import six
from keystone.common import dependency from keystone.common import dependency
from keystone import config from keystone import config
from keystone import exception from keystone import exception
@ -288,7 +290,7 @@ class V3TokenDataHelper(object):
def _populate_token_dates(self, token_data, expires=None, trust=None): def _populate_token_dates(self, token_data, expires=None, trust=None):
if not expires: if not expires:
expires = token.default_expire_time() expires = token.default_expire_time()
if not isinstance(expires, basestring): if not isinstance(expires, six.string_types):
expires = timeutils.isotime(expires, subsecond=True) expires = timeutils.isotime(expires, subsecond=True)
token_data['expires_at'] = expires token_data['expires_at'] = expires
token_data['issued_at'] = timeutils.isotime(subsecond=True) token_data['issued_at'] = timeutils.isotime(subsecond=True)
@ -359,7 +361,7 @@ class BaseProvider(provider.Provider):
token_data['access']['token']['id'] = token_id token_data['access']['token']['id'] = token_id
try: try:
expiry = token_data['access']['token']['expires'] expiry = token_data['access']['token']['expires']
if isinstance(expiry, basestring): if isinstance(expiry, six.string_types):
expiry = timeutils.normalize_time( expiry = timeutils.normalize_time(
timeutils.parse_isotime(expiry)) timeutils.parse_isotime(expiry))
data = dict(key=token_id, data = dict(key=token_id,
@ -415,7 +417,7 @@ class BaseProvider(provider.Provider):
token_id = self._get_token_id(token_data) token_id = self._get_token_id(token_data)
try: try:
expiry = token_data['token']['expires_at'] expiry = token_data['token']['expires_at']
if isinstance(expiry, basestring): if isinstance(expiry, six.string_types):
expiry = timeutils.normalize_time( expiry = timeutils.normalize_time(
timeutils.parse_isotime(expiry)) timeutils.parse_isotime(expiry))
# FIXME(gyee): is there really a need to store roles in metadata? # FIXME(gyee): is there really a need to store roles in metadata?

View File

@ -16,6 +16,8 @@
import uuid import uuid
import six
from keystone import assignment from keystone import assignment
from keystone.common import controller from keystone.common import controller
from keystone.common import dependency from keystone.common import dependency
@ -94,7 +96,7 @@ class TrustV3(controller.V3Controller):
trust['roles'] = [] trust['roles'] = []
trust_full_roles = [] trust_full_roles = []
for trust_role in trust['roles']: for trust_role in trust['roles']:
if isinstance(trust_role, basestring): if isinstance(trust_role, six.string_types):
trust_role = {'id': trust_role} trust_role = {'id': trust_role}
matching_roles = [x for x in all_roles matching_roles = [x for x in all_roles
if x['id'] == trust_role['id']] if x['id'] == trust_role['id']]