[py3] Switched to Python 3-compatible imports.

xrange/range will be dealt with in a separate commit due to the huge
number of changes.
This commit is contained in:
Aymeric Augustin 2012-07-20 16:16:57 +02:00
parent 0d914d08a0
commit ca07fda2ef
24 changed files with 54 additions and 48 deletions

View File

@ -1,8 +1,8 @@
from django.test import TestCase
from django.utils.unittest import skipUnless
from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.models import User, AnonymousUser
from django.core.management import call_command from django.core.management import call_command
from StringIO import StringIO from django.test import TestCase
from django.utils.six import StringIO
from django.utils.unittest import skipUnless
try: try:
import crypt as crypt_module import crypt as crypt_module

View File

@ -1,11 +1,10 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from StringIO import StringIO
from django.contrib.auth import models, management from django.contrib.auth import models, management
from django.contrib.auth.management.commands import changepassword from django.contrib.auth.management.commands import changepassword
from django.core.management.base import CommandError from django.core.management.base import CommandError
from django.test import TestCase from django.test import TestCase
from django.utils.six import StringIO
class GetDefaultUsernameTestCase(TestCase): class GetDefaultUsernameTestCase(TestCase):

View File

@ -1,4 +1,4 @@
from future_builtins import zip from django.utils.six.moves import zip
from django.db.backends.util import truncate_name, typecast_timestamp from django.db.backends.util import truncate_name, typecast_timestamp
from django.db.models.sql import compiler from django.db.models.sql import compiler

View File

@ -1,6 +1,6 @@
from binascii import b2a_hex from binascii import b2a_hex
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -952,7 +952,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
def test_pickle(self): def test_pickle(self):
"Testing pickling and unpickling support." "Testing pickling and unpickling support."
# Using both pickle and cPickle -- just 'cause. # Using both pickle and cPickle -- just 'cause.
import pickle, cPickle from django.utils.six.moves import cPickle
import pickle
# Creating a list of test geometries for pickling, # Creating a list of test geometries for pickling,
# and setting the SRID on some of them. # and setting the SRID on some of them.

View File

@ -5,7 +5,7 @@ models for GeoDjango and/or mapping dictionaries for use with the
Author: Travis Pinney, Dane Springmeyer, & Justin Bronn Author: Travis Pinney, Dane Springmeyer, & Justin Bronn
""" """
from future_builtins import zip from django.utils.six.moves import zip
# Requires GDAL to use. # Requires GDAL to use.
from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime

View File

@ -2,7 +2,7 @@ import base64
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -1,5 +1,5 @@
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -4,7 +4,7 @@ import time
from datetime import datetime from datetime import datetime
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -5,7 +5,7 @@ import os
import shutil import shutil
import time import time
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -2,7 +2,7 @@
import time import time
try: try:
import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle

View File

@ -16,7 +16,7 @@ try:
except ImportError: # Python 2 except ImportError: # Python 2
from urllib import unquote from urllib import unquote
from urlparse import urljoin from urlparse import urljoin
from SocketServer import ThreadingMixIn from django.utils.six.moves import socketserver
from wsgiref import simple_server from wsgiref import simple_server
from wsgiref.util import FileWrapper # for backwards compatibility from wsgiref.util import FileWrapper # for backwards compatibility
@ -200,7 +200,7 @@ class WSGIRequestHandler(simple_server.WSGIRequestHandler, object):
def run(addr, port, wsgi_handler, ipv6=False, threading=False): def run(addr, port, wsgi_handler, ipv6=False, threading=False):
server_address = (addr, port) server_address = (addr, port)
if threading: if threading:
httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {}) httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, WSGIServer), {})
else: else:
httpd_cls = WSGIServer httpd_cls = WSGIServer
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)

View File

@ -3,7 +3,7 @@ from django.db.utils import DatabaseError
try: try:
import thread import thread
except ImportError: except ImportError:
import dummy_thread as thread from django.utils.six.moves import _dummy_thread as thread
from contextlib import contextmanager from contextlib import contextmanager
from django.conf import settings from django.conf import settings

View File

@ -3,7 +3,7 @@ from __future__ import unicode_literals
import copy import copy
import sys import sys
from functools import update_wrapper from functools import update_wrapper
from future_builtins import zip from django.utils.six.moves import zip
import django.db.models.manager # Imported to register signal handler. import django.db.models.manager # Imported to register signal handler.
from django.conf import settings from django.conf import settings

View File

@ -1,4 +1,4 @@
from future_builtins import zip from django.utils.six.moves import zip
from django.core.exceptions import FieldError from django.core.exceptions import FieldError
from django.db import transaction from django.db import transaction

View File

@ -16,23 +16,23 @@ except ImportError: # Python 2
from urllib import quote, urlencode from urllib import quote, urlencode
from urlparse import parse_qsl, urljoin from urlparse import parse_qsl, urljoin
import Cookie from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix: # Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = Cookie.SimpleCookie().value_encode(';') == (';', '"\\073"') _cookie_encodes_correctly = http_cookies.SimpleCookie().value_encode(';') == (';', '"\\073"')
# See ticket #13007, http://bugs.python.org/issue2193 and http://trac.edgewall.org/ticket/2256 # See ticket #13007, http://bugs.python.org/issue2193 and http://trac.edgewall.org/ticket/2256
_tc = Cookie.SimpleCookie() _tc = http_cookies.SimpleCookie()
try: try:
_tc.load(b'foo:bar=1') _tc.load(b'foo:bar=1')
_cookie_allows_colon_in_names = True _cookie_allows_colon_in_names = True
except Cookie.CookieError: except http_cookies.CookieError:
_cookie_allows_colon_in_names = False _cookie_allows_colon_in_names = False
if _cookie_encodes_correctly and _cookie_allows_colon_in_names: if _cookie_encodes_correctly and _cookie_allows_colon_in_names:
SimpleCookie = Cookie.SimpleCookie SimpleCookie = http_cookies.SimpleCookie
else: else:
Morsel = Cookie.Morsel Morsel = http_cookies.Morsel
class SimpleCookie(Cookie.SimpleCookie): class SimpleCookie(http_cookies.SimpleCookie):
if not _cookie_encodes_correctly: if not _cookie_encodes_correctly:
def value_encode(self, val): def value_encode(self, val):
# Some browsers do not support quoted-string from RFC 2109, # Some browsers do not support quoted-string from RFC 2109,
@ -73,9 +73,9 @@ else:
M = self.get(key, Morsel()) M = self.get(key, Morsel())
M.set(key, real_value, coded_value) M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M) dict.__setitem__(self, key, M)
except Cookie.CookieError: except http_cookies.CookieError:
self.bad_cookies.add(key) self.bad_cookies.add(key)
dict.__setitem__(self, key, Cookie.Morsel()) dict.__setitem__(self, key, http_cookies.Morsel())
from django.conf import settings from django.conf import settings
@ -495,11 +495,11 @@ class QueryDict(MultiValueDict):
def parse_cookie(cookie): def parse_cookie(cookie):
if cookie == '': if cookie == '':
return {} return {}
if not isinstance(cookie, Cookie.BaseCookie): if not isinstance(cookie, http_cookies.BaseCookie):
try: try:
c = SimpleCookie() c = SimpleCookie()
c.load(cookie) c.load(cookie)
except Cookie.CookieError: except http_cookies.CookieError:
# Invalid cookie # Invalid cookie
return {} return {}
else: else:

View File

@ -103,9 +103,9 @@ import __future__
import sys, traceback, inspect, linecache, os, re import sys, traceback, inspect, linecache, os, re
import unittest, difflib, pdb, tempfile import unittest, difflib, pdb, tempfile
import warnings import warnings
from StringIO import StringIO
from django.utils import six from django.utils import six
from django.utils.six import StringIO
if sys.platform.startswith('java'): if sys.platform.startswith('java'):
# On Jython, isclass() reports some modules as classes. Patch it. # On Jython, isclass() reports some modules as classes. Patch it.

View File

@ -5,9 +5,8 @@ Comparing two html documents.
from __future__ import unicode_literals from __future__ import unicode_literals
import re import re
from HTMLParser import HTMLParseError
from django.utils.encoding import force_unicode from django.utils.encoding import force_unicode
from django.utils.html_parser import HTMLParser from django.utils.html_parser import HTMLParser, HTMLParseError
from django.utils import six from django.utils import six

View File

@ -33,7 +33,7 @@ import os, sys, time, signal
try: try:
import thread import thread
except ImportError: except ImportError:
import dummy_thread as thread from django.utils.six.moves import _dummy_thread as thread
# This import does nothing, but it's necessary to avoid some race conditions # This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 . # in the threading module. See http://code.djangoproject.com/ticket/2330 .

View File

@ -1,26 +1,28 @@
import HTMLParser as _HTMLParser from django.utils.six.moves import html_parser as _html_parser
import re import re
tagfind = re.compile('([a-zA-Z][-.a-zA-Z0-9:_]*)(?:\s|/(?!>))*') tagfind = re.compile('([a-zA-Z][-.a-zA-Z0-9:_]*)(?:\s|/(?!>))*')
class HTMLParser(_HTMLParser.HTMLParser): HTMLParseError = _html_parser.HTMLParseError
class HTMLParser(_html_parser.HTMLParser):
""" """
Patched version of stdlib's HTMLParser with patch from: Patched version of stdlib's HTMLParser with patch from:
http://bugs.python.org/issue670664 http://bugs.python.org/issue670664
""" """
def __init__(self): def __init__(self):
_HTMLParser.HTMLParser.__init__(self) _html_parser.HTMLParser.__init__(self)
self.cdata_tag = None self.cdata_tag = None
def set_cdata_mode(self, tag): def set_cdata_mode(self, tag):
try: try:
self.interesting = _HTMLParser.interesting_cdata self.interesting = _html_parser.interesting_cdata
except AttributeError: except AttributeError:
self.interesting = re.compile(r'</\s*%s\s*>' % tag.lower(), re.I) self.interesting = re.compile(r'</\s*%s\s*>' % tag.lower(), re.I)
self.cdata_tag = tag.lower() self.cdata_tag = tag.lower()
def clear_cdata_mode(self): def clear_cdata_mode(self):
self.interesting = _HTMLParser.interesting_normal self.interesting = _html_parser.interesting_normal
self.cdata_tag = None self.cdata_tag = None
# Internal -- handle starttag, return end or -1 if not terminated # Internal -- handle starttag, return end or -1 if not terminated
@ -40,7 +42,7 @@ class HTMLParser(_HTMLParser.HTMLParser):
self.lasttag = tag = match.group(1).lower() self.lasttag = tag = match.group(1).lower()
while k < endpos: while k < endpos:
m = _HTMLParser.attrfind.match(rawdata, k) m = _html_parser.attrfind.match(rawdata, k)
if not m: if not m:
break break
attrname, rest, attrvalue = m.group(1, 2, 3) attrname, rest, attrvalue = m.group(1, 2, 3)
@ -78,11 +80,11 @@ class HTMLParser(_HTMLParser.HTMLParser):
def parse_endtag(self, i): def parse_endtag(self, i):
rawdata = self.rawdata rawdata = self.rawdata
assert rawdata[i:i + 2] == "</", "unexpected call to parse_endtag" assert rawdata[i:i + 2] == "</", "unexpected call to parse_endtag"
match = _HTMLParser.endendtag.search(rawdata, i + 1) # > match = _html_parser.endendtag.search(rawdata, i + 1) # >
if not match: if not match:
return -1 return -1
j = match.end() j = match.end()
match = _HTMLParser.endtagfind.match(rawdata, i) # </ + tag + > match = _html_parser.endtagfind.match(rawdata, i) # </ + tag + >
if not match: if not match:
if self.cdata_tag is not None: # *** add *** if self.cdata_tag is not None: # *** add ***
self.handle_data(rawdata[i:j]) # *** add *** self.handle_data(rawdata[i:j]) # *** add ***

View File

@ -4,7 +4,7 @@ Where possible, we try to use the system-native version and only fall back to
these implementations if necessary. these implementations if necessary.
""" """
import __builtin__ from django.utils.six.moves import builtins
import itertools import itertools
import warnings import warnings
@ -25,9 +25,9 @@ def product(*args, **kwds):
def all(iterable): def all(iterable):
warnings.warn("django.utils.itercompat.all is deprecated; use the native version instead", warnings.warn("django.utils.itercompat.all is deprecated; use the native version instead",
DeprecationWarning) DeprecationWarning)
return __builtin__.all(iterable) return builtins.all(iterable)
def any(iterable): def any(iterable):
warnings.warn("django.utils.itercompat.any is deprecated; use the native version instead", warnings.warn("django.utils.itercompat.any is deprecated; use the native version instead",
DeprecationWarning) DeprecationWarning)
return __builtin__.any(iterable) return builtins.any(iterable)

View File

@ -351,3 +351,8 @@ _add_doc(reraise, """Reraise an exception.""")
def with_metaclass(meta, base=object): def with_metaclass(meta, base=object):
"""Create a base class with a metaclass.""" """Create a base class with a metaclass."""
return meta("NewBase", (base,), {}) return meta("NewBase", (base,), {})
### Additional customizations for Django ###
add_move(MovedModule("_dummy_thread", "dummy_thread"))

View File

@ -4,7 +4,7 @@ import re
import unicodedata import unicodedata
import warnings import warnings
from gzip import GzipFile from gzip import GzipFile
from htmlentitydefs import name2codepoint from django.utils.six.moves import html_entities
from io import BytesIO from io import BytesIO
from django.utils.encoding import force_unicode from django.utils.encoding import force_unicode
@ -349,7 +349,7 @@ def _replace_entity(match):
return match.group(0) return match.group(0)
else: else:
try: try:
return unichr(name2codepoint[text]) return unichr(html_entities.name2codepoint[text])
except (ValueError, KeyError): except (ValueError, KeyError):
return match.group(0) return match.group(0)

View File

@ -6,11 +6,11 @@ import os
import re import re
import sys import sys
import gettext as gettext_module import gettext as gettext_module
from io import StringIO
from threading import local from threading import local
from django.utils.importlib import import_module from django.utils.importlib import import_module
from django.utils.safestring import mark_safe, SafeData from django.utils.safestring import mark_safe, SafeData
from django.utils.six import StringIO
# Translations are cached in a dictionary for every language+app tuple. # Translations are cached in a dictionary for every language+app tuple.