Skip to content

Commit

Permalink
[py3] Replaced unicode/str by six.text_type/bytes.
Browse files Browse the repository at this point in the history
  • Loading branch information
aaugustin committed Jul 22, 2012
1 parent 3cb2457 commit bdca5ea
Show file tree
Hide file tree
Showing 96 changed files with 376 additions and 294 deletions.
2 changes: 1 addition & 1 deletion django/contrib/admin/helpers.py
Expand Up @@ -189,7 +189,7 @@ def contents(self):
if value is None:
result_repr = EMPTY_CHANGELIST_VALUE
elif isinstance(f.rel, ManyToManyRel):
result_repr = ", ".join(map(unicode, value.all()))
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f)
return conditional_escape(result_repr)
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/admin/util.py
Expand Up @@ -275,10 +275,10 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
except models.FieldDoesNotExist:
if name == "__unicode__":
label = force_unicode(model._meta.verbose_name)
attr = unicode
attr = six.text_type
elif name == "__str__":
label = smart_str(model._meta.verbose_name)
attr = str
attr = bytes
else:
if callable(name):
attr = name
Expand Down
3 changes: 2 additions & 1 deletion django/contrib/admin/widgets.py
Expand Up @@ -15,6 +15,7 @@
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
from django.utils import six


class FilteredSelectMultiple(forms.SelectMultiple):
Expand Down Expand Up @@ -121,7 +122,7 @@ def url_params_from_lookup_dict(lookups):
# See django.db.fields.BooleanField.get_prep_lookup
v = ('0', '1')[v]
else:
v = unicode(v)
v = six.text_type(v)
items.append((k, v))
params.update(dict(items))
return params
Expand Down
9 changes: 5 additions & 4 deletions django/contrib/auth/models.py
Expand Up @@ -8,6 +8,7 @@
from django.db.models.manager import EmptyManager
from django.utils.crypto import get_random_string
from django.utils.encoding import smart_str
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone

Expand Down Expand Up @@ -79,9 +80,9 @@ class Meta:

def __unicode__(self):
return "%s | %s | %s" % (
unicode(self.content_type.app_label),
unicode(self.content_type),
unicode(self.name))
six.text_type(self.content_type.app_label),
six.text_type(self.content_type),
six.text_type(self.name))

def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
Expand Down Expand Up @@ -421,7 +422,7 @@ def __unicode__(self):
return 'AnonymousUser'

def __str__(self):
return unicode(self).encode('utf-8')
return six.text_type(self).encode('utf-8')

def __eq__(self, other):
return isinstance(other, self.__class__)
Expand Down
5 changes: 3 additions & 2 deletions django/contrib/auth/tokens.py
Expand Up @@ -2,6 +2,7 @@
from django.conf import settings
from django.utils.http import int_to_base36, base36_to_int
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils import six

class PasswordResetTokenGenerator(object):
"""
Expand Down Expand Up @@ -56,8 +57,8 @@ def _make_token_with_timestamp(self, user, timestamp):
# Ensure results are consistent across DB backends
login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None)

value = (unicode(user.id) + user.password +
unicode(login_timestamp) + unicode(timestamp))
value = (six.text_type(user.id) + user.password +
six.text_type(login_timestamp) + six.text_type(timestamp))
hash = salted_hmac(key_salt, value).hexdigest()[::2]
return "%s-%s" % (ts_b36, hash)

Expand Down
3 changes: 2 additions & 1 deletion django/contrib/contenttypes/tests.py
Expand Up @@ -9,6 +9,7 @@
from django.http import HttpRequest, Http404
from django.test import TestCase
from django.utils.encoding import smart_str
from django.utils import six


class ConcreteModel(models.Model):
Expand Down Expand Up @@ -271,4 +272,4 @@ def test_missing_model(self):
app_label = 'contenttypes',
model = 'OldModel',
)
self.assertEqual(unicode(ct), 'Old model')
self.assertEqual(six.text_type(ct), 'Old model')
5 changes: 3 additions & 2 deletions django/contrib/formtools/wizard/views.py
Expand Up @@ -7,6 +7,7 @@
from django.views.generic import TemplateView
from django.utils.datastructures import SortedDict
from django.utils.decorators import classonlymethod
from django.utils import six

from django.contrib.formtools.wizard.storage import get_storage
from django.contrib.formtools.wizard.storage.exceptions import NoFileStorageConfigured
Expand Down Expand Up @@ -157,10 +158,10 @@ def get_initkwargs(cls, form_list, initial_dict=None,
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
init_form_list[unicode(form[0])] = form[1]
init_form_list[six.text_type(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
init_form_list[unicode(i)] = form
init_form_list[six.text_type(i)] = form

# walk through the new created list of forms
for form in init_form_list.itervalues():
Expand Down
7 changes: 4 additions & 3 deletions django/contrib/gis/db/backends/base.py
Expand Up @@ -4,6 +4,7 @@
"""
import re
from django.contrib.gis import gdal
from django.utils import six

class BaseSpatialOperations(object):
"""
Expand Down Expand Up @@ -88,7 +89,7 @@ def convert_geom(self, geom_val, geom_field):

# For quoting column values, rather than columns.
def geo_quote_name(self, name):
if isinstance(name, unicode):
if isinstance(name, six.text_type):
name = name.encode('ascii')
return "'%s'" % name

Expand Down Expand Up @@ -330,6 +331,6 @@ def __unicode__(self):
it will be 'pretty' OGC WKT.
"""
try:
return unicode(self.srs)
return six.text_type(self.srs)
except:
return unicode(self.wkt)
return six.text_type(self.wkt)
2 changes: 1 addition & 1 deletion django/contrib/gis/db/backends/util.py
Expand Up @@ -12,7 +12,7 @@ def gqn(val):
backend quotename function).
"""
if isinstance(val, six.string_types):
if isinstance(val, unicode): val = val.encode('ascii')
if isinstance(val, six.text_type): val = val.encode('ascii')
return "'%s'" % val
else:
return str(val)
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/gdal/geometries.py
Expand Up @@ -81,7 +81,7 @@ def __init__(self, geom_input, srs=None):
# Constructing the geometry,
if str_instance:
# Checking if unicode
if isinstance(geom_input, unicode):
if isinstance(geom_input, six.text_type):
# Encoding to ASCII, WKT or HEX doesn't need any more.
geom_input = geom_input.encode('ascii')

Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/gdal/srs.py
Expand Up @@ -56,7 +56,7 @@ def __init__(self, srs_input=''):

if isinstance(srs_input, six.string_types):
# Encoding to ASCII if unicode passed in.
if isinstance(srs_input, unicode):
if isinstance(srs_input, six.text_type):
srs_input = srs_input.encode('ascii')
try:
# If SRID is a string, e.g., '4326', then make acceptable
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/geos/geometry.py
Expand Up @@ -55,7 +55,7 @@ def __init__(self, geo_input, srid=None):
(SRID) number for this Geometry. If not set, the SRID will be None.
"""
if isinstance(geo_input, six.string_types):
if isinstance(geo_input, unicode):
if isinstance(geo_input, six.text_type):
# Encoding to ASCII, WKT or HEXEWKB doesn't need any more.
geo_input = geo_input.encode('ascii')

Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/geos/tests/test_io.py
Expand Up @@ -13,7 +13,7 @@ def test01_wktreader(self):
# read() should return a GEOSGeometry
ref = GEOSGeometry(wkt)
g1 = wkt_r.read(wkt)
g2 = wkt_r.read(unicode(wkt))
g2 = wkt_r.read(six.text_type(wkt))

for geom in (g1, g2):
self.assertEqual(ref, geom)
Expand Down
3 changes: 2 additions & 1 deletion django/contrib/gis/tests/geoapp/tests.py
Expand Up @@ -11,6 +11,7 @@
no_mysql, no_oracle, no_spatialite,
mysql, oracle, postgis, spatialite)
from django.test import TestCase
from django.utils import six

from .models import Country, City, PennsylvaniaCity, State, Track

Expand Down Expand Up @@ -663,7 +664,7 @@ def test27_snap_to_grid(self):
# Let's try and break snap_to_grid() with bad combinations of arguments.
for bad_args in ((), range(3), range(5)):
self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args)
for bad_args in (('1.0',), (1.0, None), tuple(map(unicode, range(4)))):
for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args)

# Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/utils/layermapping.py
Expand Up @@ -330,7 +330,7 @@ def verify_ogr_field(self, ogr_field, model_field):
if self.encoding:
# The encoding for OGR data sources may be specified here
# (e.g., 'cp437' for Census Bureau boundary files).
val = unicode(ogr_field.value, self.encoding)
val = six.text_type(ogr_field.value, self.encoding)
else:
val = ogr_field.value
if model_field.max_length and len(val) > model_field.max_length:
Expand Down
5 changes: 3 additions & 2 deletions django/contrib/localflavor/mx/forms.py
Expand Up @@ -7,6 +7,7 @@

from django.forms import ValidationError
from django.forms.fields import Select, RegexField
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.core.validators import EMPTY_VALUES
from django.contrib.localflavor.mx.mx_states import STATE_CHOICES
Expand Down Expand Up @@ -155,7 +156,7 @@ def _checksum(self, rfc):
elif checksum == 11:
return '0'

return unicode(checksum)
return six.text_type(checksum)

def _has_inconvenient_word(self, rfc):
first_four = rfc[:4]
Expand Down Expand Up @@ -219,7 +220,7 @@ def _checksum(self, value):

if checksum == 10:
return '0'
return unicode(checksum)
return six.text_type(checksum)

def _has_inconvenient_word(self, curp):
first_four = curp[:4]
Expand Down
5 changes: 3 additions & 2 deletions django/contrib/localflavor/se/utils.py
@@ -1,4 +1,5 @@
import datetime
from django.utils import six

def id_number_checksum(gd):
"""
Expand Down Expand Up @@ -65,15 +66,15 @@ def validate_id_birthday(gd, fix_coordination_number_day=True):

def format_personal_id_number(birth_day, gd):
# birth_day.strftime cannot be used, since it does not support dates < 1900
return unicode(str(birth_day.year) + gd['month'] + gd['day'] + gd['serial'] + gd['checksum'])
return six.text_type(str(birth_day.year) + gd['month'] + gd['day'] + gd['serial'] + gd['checksum'])

def format_organisation_number(gd):
if gd['century'] is None:
century = ''
else:
century = gd['century']

return unicode(century + gd['year'] + gd['month'] + gd['day'] + gd['serial'] + gd['checksum'])
return six.text_type(century + gd['year'] + gd['month'] + gd['day'] + gd['serial'] + gd['checksum'])

def valid_organisation(gd):
return gd['century'] in (None, 16) and \
Expand Down
3 changes: 2 additions & 1 deletion django/core/management/commands/inspectdb.py
Expand Up @@ -3,6 +3,7 @@

from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from django.utils import six

class Command(NoArgsCommand):
help = "Introspects the database tables in the given database and outputs a Django model module."
Expand Down Expand Up @@ -115,7 +116,7 @@ def handle_inspection(self, options):

if att_name[0].isdigit():
att_name = 'number_%s' % att_name
extra_params['db_column'] = unicode(column_name)
extra_params['db_column'] = six.text_type(column_name)
comment_notes.append("Field renamed because it wasn't a "
"valid Python identifier.")

Expand Down
4 changes: 2 additions & 2 deletions django/core/management/validation.py
Expand Up @@ -120,7 +120,7 @@ def get_validation_errors(outfile, app=None):
e.add(opts, "'%s' has a relation with model %s, which has either not been installed or is abstract." % (f.name, f.rel.to))
# it is a string and we could not find the model it refers to
# so skip the next section
if isinstance(f.rel.to, (str, unicode)):
if isinstance(f.rel.to, six.string_types):
continue

# Make sure the related field specified by a ForeignKey is unique
Expand Down Expand Up @@ -162,7 +162,7 @@ def get_validation_errors(outfile, app=None):
e.add(opts, "'%s' has an m2m relation with model %s, which has either not been installed or is abstract." % (f.name, f.rel.to))
# it is a string and we could not find the model it refers to
# so skip the next section
if isinstance(f.rel.to, (str, unicode)):
if isinstance(f.rel.to, six.string_types):
continue

# Check that the field is not set to unique. ManyToManyFields do not support unique.
Expand Down
2 changes: 1 addition & 1 deletion django/core/urlresolvers.py
Expand Up @@ -169,7 +169,7 @@ def regex(self):
except re.error as e:
raise ImproperlyConfigured(
'"%s" is not a valid regular expression: %s' %
(regex, unicode(e)))
(regex, six.text_type(e)))

self._regex_dict[language_code] = compiled_regex
return self._regex_dict[language_code]
Expand Down
7 changes: 4 additions & 3 deletions django/db/backends/__init__.py
Expand Up @@ -12,6 +12,7 @@
from django.db.transaction import TransactionManagementError
from django.utils.functional import cached_property
from django.utils.importlib import import_module
from django.utils import six
from django.utils.timezone import is_aware


Expand Down Expand Up @@ -808,7 +809,7 @@ def value_to_db_date(self, value):
"""
if value is None:
return None
return unicode(value)
return six.text_type(value)

def value_to_db_datetime(self, value):
"""
Expand All @@ -817,7 +818,7 @@ def value_to_db_datetime(self, value):
"""
if value is None:
return None
return unicode(value)
return six.text_type(value)

def value_to_db_time(self, value):
"""
Expand All @@ -828,7 +829,7 @@ def value_to_db_time(self, value):
return None
if is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return unicode(value)
return six.text_type(value)

def value_to_db_decimal(self, value, max_digits, decimal_places):
"""
Expand Down
8 changes: 4 additions & 4 deletions django/db/backends/mysql/base.py
Expand Up @@ -297,7 +297,7 @@ def value_to_db_datetime(self, value):
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")

# MySQL doesn't support microseconds
return unicode(value.replace(microsecond=0))
return six.text_type(value.replace(microsecond=0))

def value_to_db_time(self, value):
if value is None:
Expand All @@ -308,7 +308,7 @@ def value_to_db_time(self, value):
raise ValueError("MySQL backend does not support timezone-aware times.")

# MySQL doesn't support microseconds
return unicode(value.replace(microsecond=0))
return six.text_type(value.replace(microsecond=0))

def year_lookup_bounds(self, value):
# Again, no microseconds
Expand Down Expand Up @@ -399,8 +399,8 @@ def _cursor(self):
kwargs['client_flag'] = CLIENT.FOUND_ROWS
kwargs.update(settings_dict['OPTIONS'])
self.connection = Database.connect(**kwargs)
self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode]
self.connection.encoders[SafeString] = self.connection.encoders[str]
self.connection.encoders[SafeUnicode] = self.connection.encoders[six.text_type]
self.connection.encoders[SafeString] = self.connection.encoders[bytes]
connection_created.send(sender=self.__class__, connection=self)
cursor = self.connection.cursor()
if new_connection:
Expand Down
2 changes: 1 addition & 1 deletion django/db/backends/oracle/base.py
Expand Up @@ -356,7 +356,7 @@ def value_to_db_datetime(self, value):
else:
raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

return unicode(value)
return six.text_type(value)

def value_to_db_time(self, value):
if value is None:
Expand Down

0 comments on commit bdca5ea

Please sign in to comment.