~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to django/utils/encoding.py

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2009-07-29 11:26:28 UTC
  • mfrom: (1.1.8 upstream) (4.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20090729112628-pg09ino8sz0sj21t
Tags: 1.1-1
* New upstream release.
* Merge from experimental:
  - Ship FastCGI initscript and /etc/default file in python-django's examples
    directory (Closes: #538863)
  - Drop "05_10539-sphinx06-compatibility.diff"; it has been applied
    upstream.
  - Bump Standards-Version to 3.8.2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
import types
2
2
import urllib
 
3
import locale
3
4
import datetime
 
5
import codecs
 
6
 
4
7
from django.utils.functional import Promise
5
8
 
 
9
try:
 
10
    from decimal import Decimal
 
11
except ImportError:
 
12
    from django.utils._decimal import Decimal # Python 2.3 fallback
 
13
 
 
14
 
6
15
class DjangoUnicodeDecodeError(UnicodeDecodeError):
7
16
    def __init__(self, obj, *args):
8
17
        self.obj = obj
34
43
        return s
35
44
    return force_unicode(s, encoding, strings_only, errors)
36
45
 
 
46
def is_protected_type(obj):
 
47
    """Determine if the object instance is of a protected type.
 
48
 
 
49
    Objects of protected types are preserved as-is when passed to
 
50
    force_unicode(strings_only=True).
 
51
    """
 
52
    return isinstance(obj, (
 
53
        types.NoneType,
 
54
        int, long,
 
55
        datetime.datetime, datetime.date, datetime.time,
 
56
        float, Decimal)
 
57
    )
 
58
 
37
59
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
38
60
    """
39
61
    Similar to smart_unicode, except that lazy instances are resolved to
41
63
 
42
64
    If strings_only is True, don't convert (some) non-string-like objects.
43
65
    """
44
 
    if strings_only and isinstance(s, (types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float)):
 
66
    if strings_only and is_protected_type(s):
45
67
        return s
46
68
    try:
47
69
        if not isinstance(s, basestring,):
116
138
        return iri
117
139
    return urllib.quote(smart_str(iri), safe='/#%[]=:;$&()+,!?*')
118
140
 
 
141
 
 
142
# The encoding of the default system locale but falls back to the
 
143
# given fallback encoding if the encoding is unsupported by python or could
 
144
# not be determined.  See tickets #10335 and #5846
 
145
try:
 
146
    DEFAULT_LOCALE_ENCODING = locale.getdefaultlocale()[1] or 'ascii'
 
147
    codecs.lookup(DEFAULT_LOCALE_ENCODING)
 
148
except:
 
149
    DEFAULT_LOCALE_ENCODING = 'ascii'