Permalink
Browse files

Replaced many smart_bytes by force_bytes

In all those occurrences, we didn't care about preserving the
lazy status of the strings, but we really wanted to obtain a
real bytestring.
  • Loading branch information...
1 parent 9eafb65 commit ebc773ada3e4f40cf5084268387b873d7fe22e8b @claudep claudep committed Aug 28, 2012
@@ -12,7 +12,7 @@
from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils import timezone
-from django.utils.encoding import force_text, smart_text, smart_bytes
+from django.utils.encoding import force_str, force_text, smart_text
from django.utils import six
from django.utils.translation import ungettext
from django.core.urlresolvers import reverse
@@ -277,7 +277,7 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
label = force_text(model._meta.verbose_name)
attr = six.text_type
elif name == "__str__":
- label = smart_bytes(model._meta.verbose_name)
+ label = force_str(model._meta.verbose_name)
attr = bytes
else:
if callable(name):
@@ -6,7 +6,7 @@
from django.db import models
from django.db.models.fields import FieldDoesNotExist
from django.utils.datastructures import SortedDict
-from django.utils.encoding import force_text, smart_bytes
+from django.utils.encoding import force_str, force_text
from django.utils.translation import ugettext, ugettext_lazy
from django.utils.http import urlencode
@@ -94,7 +94,7 @@ def get_filters(self, request):
# 'key' will be used as a keyword argument later, so Python
# requires it to be a string.
del lookup_params[key]
- lookup_params[smart_bytes(key)] = value
+ lookup_params[force_str(key)] = value
if not self.model_admin.lookup_allowed(key, value):
raise SuspiciousOperation("Filtering by %s not allowed" % key)
@@ -6,7 +6,7 @@
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
try:
import docutils.core
import docutils.nodes
@@ -66,7 +66,7 @@ def parse_rst(text, default_reference_context, thing_being_parsed=None):
"link_base" : reverse('django-admindocs-docroot').rstrip('/')
}
if thing_being_parsed:
- thing_being_parsed = smart_bytes("<%s>" % thing_being_parsed)
+ thing_being_parsed = force_bytes("<%s>" % thing_being_parsed)
parts = docutils.core.publish_parts(text, source_path=thing_being_parsed,
destination_path=None, writer_name='html',
settings_overrides=overrides)
@@ -8,7 +8,7 @@
from django.test.signals import setting_changed
from django.utils import importlib
from django.utils.datastructures import SortedDict
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import (
pbkdf2, constant_time_compare, get_random_string)
@@ -299,7 +299,7 @@ class SHA1PasswordHasher(BasePasswordHasher):
def encode(self, password, salt):
assert password
assert salt and '$' not in salt
- hash = hashlib.sha1(smart_bytes(salt + password)).hexdigest()
+ hash = hashlib.sha1(force_bytes(salt + password)).hexdigest()
return "%s$%s$%s" % (self.algorithm, salt, hash)
def verify(self, password, encoded):
@@ -327,7 +327,7 @@ class MD5PasswordHasher(BasePasswordHasher):
def encode(self, password, salt):
assert password
assert salt and '$' not in salt
- hash = hashlib.md5(smart_bytes(salt + password)).hexdigest()
+ hash = hashlib.md5(force_bytes(salt + password)).hexdigest()
return "%s$%s$%s" % (self.algorithm, salt, hash)
def verify(self, password, encoded):
@@ -361,7 +361,7 @@ def salt(self):
return ''
def encode(self, password, salt):
- return hashlib.md5(smart_bytes(password)).hexdigest()
+ return hashlib.md5(force_bytes(password)).hexdigest()
def verify(self, password, encoded):
encoded_2 = self.encode(password, '')
@@ -8,7 +8,6 @@
from django.contrib.gis.db.models.fields import GeometryField
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import get_model
-from django.utils.encoding import smart_bytes
from django.utils import six
from django.utils.translation import ugettext as _
@@ -61,7 +60,7 @@ def sitemap(request, sitemaps, section=None):
raise Http404(_("Page %s empty") % page)
except PageNotAnInteger:
raise Http404(_("No page '%s'") % page)
- xml = smart_bytes(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}))
+ xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})
return HttpResponse(xml, content_type='application/xml')
def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):
@@ -13,7 +13,7 @@
from django import template
from django.conf import settings
-from django.utils.encoding import smart_bytes, force_text
+from django.utils.encoding import force_bytes, force_text
from django.utils.safestring import mark_safe
register = template.Library()
@@ -27,7 +27,7 @@ def textile(value):
raise template.TemplateSyntaxError("Error in 'textile' filter: The Python textile library isn't installed.")
return force_text(value)
else:
- return mark_safe(force_text(textile.textile(smart_bytes(value), encoding='utf-8', output='utf-8')))
+ return mark_safe(force_text(textile.textile(force_bytes(value), encoding='utf-8', output='utf-8')))
@register.filter(is_safe=True)
def markdown(value, arg=''):
@@ -80,5 +80,5 @@ def restructuredtext(value):
return force_text(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
- parts = publish_parts(source=smart_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
+ parts = publish_parts(source=force_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
return mark_safe(force_text(parts["fragment"]))
@@ -14,7 +14,7 @@
from django.utils.crypto import get_random_string
from django.utils.crypto import salted_hmac
from django.utils import timezone
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
class CreateError(Exception):
"""
@@ -84,7 +84,7 @@ def encode(self, session_dict):
return base64.b64encode(hash.encode() + b":" + pickled).decode('ascii')
def decode(self, session_data):
- encoded_data = base64.b64decode(smart_bytes(session_data))
+ encoded_data = base64.b64decode(force_bytes(session_data))
try:
# could produce ValueError if there is no ':'
hash, pickled = encoded_data.split(b':', 1)
@@ -16,7 +16,7 @@
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.utils.datastructures import SortedDict
-from django.utils.encoding import force_text, smart_bytes
+from django.utils.encoding import force_bytes, force_text
from django.utils.functional import LazyObject
from django.utils.importlib import import_module
@@ -118,7 +118,7 @@ def hashed_name(self, name, content=None):
return urlunsplit(unparsed_name)
def cache_key(self, name):
- return 'staticfiles:%s' % hashlib.md5(smart_bytes(name)).hexdigest()
+ return 'staticfiles:%s' % hashlib.md5(force_bytes(name)).hexdigest()
def url(self, name, force=False):
"""
@@ -254,7 +254,7 @@ def post_process(self, paths, dry_run=False, **options):
if hashed_file_exists:
self.delete(hashed_name)
# then save the processed result
- content_file = ContentFile(smart_bytes(content))
+ content_file = ContentFile(force_bytes(content))
saved_name = self._save(hashed_name, content_file)
hashed_name = force_text(saved_name.replace('\\', '/'))
processed = True
@@ -12,7 +12,7 @@
from django.core.cache.backends.base import BaseCache
from django.db import connections, router, transaction, DatabaseError
from django.utils import timezone
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
class Options(object):
@@ -73,7 +73,7 @@ def get(self, key, default=None, version=None):
transaction.commit_unless_managed(using=db)
return default
value = connections[db].ops.process_clob(row[1])
- return pickle.loads(base64.b64decode(smart_bytes(value)))
+ return pickle.loads(base64.b64decode(force_bytes(value)))
def set(self, key, value, timeout=None, version=None):
key = self.make_key(key, version=version)
@@ -10,7 +10,7 @@
import pickle
from django.core.cache.backends.base import BaseCache
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
class FileBasedCache(BaseCache):
def __init__(self, dir, params):
@@ -137,7 +137,7 @@ def _key_to_file(self, key):
Thus, a cache key of "foo" gets turnned into a file named
``{cache-dir}ac/bd/18db4cc2f85cedef654fccc4a4d8``.
"""
- path = hashlib.md5(smart_bytes(key)).hexdigest()
+ path = hashlib.md5(force_bytes(key)).hexdigest()
path = os.path.join(path[:2], path[2:4], path[4:])
return os.path.join(self._dir, path)
@@ -3,7 +3,7 @@
import os
from io import BytesIO, UnsupportedOperation
-from django.utils.encoding import smart_bytes, smart_text
+from django.utils.encoding import smart_text
from django.core.files.utils import FileProxyMixin
from django.utils.encoding import python_2_unicode_compatible
@@ -12,7 +12,6 @@
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer as PythonDeserializer
-from django.utils.encoding import smart_bytes
from django.utils import six
from django.utils.timezone import is_aware
@@ -12,7 +12,6 @@
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer as PythonDeserializer
-from django.utils.encoding import smart_bytes
from django.utils import six
@@ -51,7 +51,7 @@ def _setup_environment(environ):
from django.db.backends.oracle.client import DatabaseClient
from django.db.backends.oracle.creation import DatabaseCreation
from django.db.backends.oracle.introspection import DatabaseIntrospection
-from django.utils.encoding import smart_bytes, force_text
+from django.utils.encoding import force_bytes, force_text
from django.utils import six
from django.utils import timezone
@@ -64,7 +64,7 @@ def _setup_environment(environ):
if int(Database.version.split('.', 1)[0]) >= 5 and not hasattr(Database, 'UNICODE'):
convert_unicode = force_text
else:
- convert_unicode = smart_bytes
+ convert_unicode = force_bytes
class DatabaseFeatures(BaseDatabaseFeatures):
@@ -602,9 +602,9 @@ def __init__(self, param, cursor, strings_only=False):
elif param is False:
param = "0"
if hasattr(param, 'bind_parameter'):
- self.smart_bytes = param.bind_parameter(cursor)
+ self.force_bytes = param.bind_parameter(cursor)
else:
- self.smart_bytes = convert_unicode(param, cursor.charset,
+ self.force_bytes = convert_unicode(param, cursor.charset,
strings_only)
if hasattr(param, 'input_size'):
# If parameter has `input_size` attribute, use that.
@@ -683,7 +683,7 @@ def _guess_input_sizes(self, params_list):
self.setinputsizes(*sizes)
def _param_generator(self, params):
- return [p.smart_bytes for p in params]
+ return [p.force_bytes for p in params]
def execute(self, query, params=None):
if params is None:
@@ -6,7 +6,7 @@
from time import time
from django.conf import settings
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
from django.utils.log import getLogger
from django.utils.timezone import utc
@@ -138,7 +138,7 @@ def truncate_name(name, length=None, hash_len=4):
if length is None or len(name) <= length:
return name
- hsh = hashlib.md5(smart_bytes(name)).hexdigest()[:hash_len]
+ hsh = hashlib.md5(force_bytes(name)).hexdigest()[:hash_len]
return '%s%s' % (name[:length-hash_len], hsh)
def format_number(value, max_digits, decimal_places):
View
@@ -85,7 +85,7 @@ def _BaseCookie__set(self, key, real_value, coded_value):
from django.http.multipartparser import MultiPartParser
from django.http.utils import *
from django.utils.datastructures import MultiValueDict, ImmutableList
-from django.utils.encoding import smart_bytes, smart_str, iri_to_uri, force_text
+from django.utils.encoding import force_bytes, force_text, smart_str, iri_to_uri
from django.utils.http import cookie_date
from django.utils import six
from django.utils import timezone
@@ -489,13 +489,13 @@ def urlencode(self, safe=None):
"""
output = []
if safe:
- safe = smart_bytes(safe, self.encoding)
+ safe = force_bytes(safe, self.encoding)
encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
encode = lambda k, v: urlencode({k: v})
for k, list_ in self.lists():
- k = smart_bytes(k, self.encoding)
- output.extend([encode(k, smart_bytes(v, self.encoding))
+ k = force_bytes(k, self.encoding)
+ output.extend([encode(k, force_bytes(v, self.encoding))
for v in list_])
return '&'.join(output)
@@ -680,7 +680,7 @@ def make_bytes(value):
# force conversion to bytes in case chunk is a subclass
return bytes(value)
return b''.join(make_bytes(e) for e in self._container)
- return b''.join(smart_bytes(e, self._charset) for e in self._container)
+ return b''.join(force_bytes(e, self._charset) for e in self._container)
@content.setter
def content(self, value):
@@ -4,7 +4,7 @@
from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist
from django.template import resolve_variable
from django.core.cache import cache
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
from django.utils.http import urlquote
register = Library()
@@ -26,8 +26,8 @@ def render(self, context):
except (ValueError, TypeError):
raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
# Build a key for this fragment and all vary-on's.
- key = smart_bytes(':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
- args = hashlib.md5(key)
+ key = ':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])
+ args = hashlib.md5(force_bytes(key))
cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())
value = cache.get(cache_key)
if value is None:
View
@@ -21,7 +21,7 @@
from django.template import TemplateDoesNotExist
from django.test import signals
from django.utils.functional import curry
-from django.utils.encoding import smart_bytes
+from django.utils.encoding import force_bytes
from django.utils.http import urlencode
from django.utils.importlib import import_module
from django.utils.itercompat import is_iterable
@@ -110,7 +110,7 @@ def encode_multipart(boundary, data):
as an application/octet-stream; otherwise, str(value) will be sent.
"""
lines = []
- to_bytes = lambda s: smart_bytes(s, settings.DEFAULT_CHARSET)
+ to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
# Not by any means perfect, but good enough for our purposes.
is_file = lambda thing: hasattr(thing, "read") and callable(thing.read)
@@ -147,7 +147,7 @@ def encode_multipart(boundary, data):
return b'\r\n'.join(lines)
def encode_file(boundary, key, file):
- to_bytes = lambda s: smart_bytes(s, settings.DEFAULT_CHARSET)
+ to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
content_type = mimetypes.guess_type(file.name)[0]
if content_type is None:
content_type = 'application/octet-stream'
@@ -222,7 +222,7 @@ def _encode_data(self, data, content_type, ):
charset = match.group(1)
else:
charset = settings.DEFAULT_CHARSET
- return smart_bytes(data, encoding=charset)
+ return force_bytes(data, encoding=charset)
def _get_path(self, parsed):
# If there are parameters, add them
@@ -293,7 +293,7 @@ def delete(self, path, data='', content_type='application/octet-stream',
def generic(self, method, path,
data='', content_type='application/octet-stream', **extra):
parsed = urlparse(path)
- data = smart_bytes(data, settings.DEFAULT_CHARSET)
+ data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': parsed[4],
Oops, something went wrong.

0 comments on commit ebc773a

Please sign in to comment.