Merge branch 'master' into schema-alteration

This commit is contained in:
Andrew Godwin 2013-07-02 10:49:53 +01:00
commit b1e0ec06f0
240 changed files with 694 additions and 4096 deletions

View File

@ -1,6 +1,6 @@
Thanks for downloading Django. Thanks for downloading Django.
To install it, make sure you have Python 2.6 or greater installed. Then run To install it, make sure you have Python 2.7 or greater installed. Then run
this command from the command prompt: this command from the command prompt:
python setup.py install python setup.py install
@ -12,7 +12,6 @@ site-packages directory, which is located wherever your Python installation
lives. Some places you might check are: lives. Some places you might check are:
/usr/lib/python2.7/site-packages (Unix, Python 2.7) /usr/lib/python2.7/site-packages (Unix, Python 2.7)
/usr/lib/python2.6/site-packages (Unix, Python 2.6)
C:\\PYTHON\site-packages (Windows) C:\\PYTHON\site-packages (Windows)
For more detailed instructions, see docs/intro/install.txt. For more detailed instructions, see docs/intro/install.txt.

View File

@ -1,19 +0,0 @@
#!/usr/bin/env python
"""
Daily cleanup job.
Can be run as a cronjob to clean out old data from the database (only expired
sessions at the moment).
"""
import warnings
from django.core import management
if __name__ == "__main__":
warnings.warn(
"The `daily_cleanup` script has been deprecated "
"in favor of `django-admin.py clearsessions`.",
DeprecationWarning)
management.call_command('clearsessions')

View File

@ -59,14 +59,10 @@ class LazySettings(LazyObject):
Setup logging from LOGGING_CONFIG and LOGGING settings. Setup logging from LOGGING_CONFIG and LOGGING settings.
""" """
if not sys.warnoptions: if not sys.warnoptions:
try: # Route warnings through python logging
# Route warnings through python logging logging.captureWarnings(True)
logging.captureWarnings(True) # Allow DeprecationWarnings through the warnings filters
# Allow DeprecationWarnings through the warnings filters warnings.simplefilter("default", DeprecationWarning)
warnings.simplefilter("default", DeprecationWarning)
except AttributeError:
# No captureWarnings on Python 2.6, DeprecationWarnings are on anyway
pass
if self.LOGGING_CONFIG: if self.LOGGING_CONFIG:
from django.utils.log import DEFAULT_LOGGING from django.utils.log import DEFAULT_LOGGING
@ -132,19 +128,17 @@ class Settings(BaseSettings):
% (self.SETTINGS_MODULE, e) % (self.SETTINGS_MODULE, e)
) )
# Settings that should be converted into tuples if they're mistakenly entered
# as strings.
tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
for setting in dir(mod): for setting in dir(mod):
if setting == setting.upper(): if setting == setting.upper():
setting_value = getattr(mod, setting) setting_value = getattr(mod, setting)
if setting in tuple_settings and \ if setting in tuple_settings and \
isinstance(setting_value, six.string_types): isinstance(setting_value, six.string_types):
warnings.warn("The %s setting must be a tuple. Please fix your " raise ImproperlyConfigured("The %s setting must be a tuple. "
"settings, as auto-correction is now deprecated." % setting, "Please fix your settings." % setting)
DeprecationWarning, stacklevel=2)
setting_value = (setting_value,) # In case the user forgot the comma.
setattr(self, setting, setting_value) setattr(self, setting, setting_value)
if not self.SECRET_KEY: if not self.SECRET_KEY:

View File

@ -562,7 +562,7 @@ MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
########### ###########
# The callable to use to configure logging # The callable to use to configure logging
LOGGING_CONFIG = 'django.utils.log.dictConfig' LOGGING_CONFIG = 'logging.config.dictConfig'
# Custom logging configuration. # Custom logging configuration.
LOGGING = {} LOGGING = {}

View File

@ -3,7 +3,7 @@ import warnings
from django.conf.urls import patterns from django.conf.urls import patterns
warnings.warn("django.conf.urls.shortcut will be removed in Django 1.8.", warnings.warn("django.conf.urls.shortcut will be removed in Django 1.8.",
PendingDeprecationWarning) DeprecationWarning)
urlpatterns = patterns('django.views', urlpatterns = patterns('django.views',
(r'^(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'), (r'^(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'),

View File

@ -76,7 +76,7 @@ csrf_protect_m = method_decorator(csrf_protect)
class RenameBaseModelAdminMethods(forms.MediaDefiningClass, RenameMethodsBase): class RenameBaseModelAdminMethods(forms.MediaDefiningClass, RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('queryset', 'get_queryset', PendingDeprecationWarning), ('queryset', 'get_queryset', DeprecationWarning),
) )

View File

@ -1,8 +1,8 @@
import os import os
from unittest import SkipTest
from django.test import LiveServerTestCase from django.test import LiveServerTestCase
from django.utils.module_loading import import_by_path from django.utils.module_loading import import_by_path
from django.utils.unittest import SkipTest
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
import datetime import datetime
import decimal import decimal
from django.contrib.auth import get_permission_codename
from django.db import models from django.db import models
from django.db.models.constants import LOOKUP_SEP from django.db.models.constants import LOOKUP_SEP
from django.db.models.deletion import Collector from django.db.models.deletion import Collector
@ -119,7 +120,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using):
opts.model_name), opts.model_name),
None, (quote(obj._get_pk_val()),)) None, (quote(obj._get_pk_val()),))
p = '%s.%s' % (opts.app_label, p = '%s.%s' % (opts.app_label,
opts.get_delete_permission()) get_permission_codename('delete', opts))
if not user.has_perm(p): if not user.has_perm(p):
perms_needed.add(opts.verbose_name) perms_needed.add(opts.verbose_name)
# Display a link to the admin page. # Display a link to the admin page.

View File

@ -52,7 +52,7 @@ def _is_changelist_popup(request):
warnings.warn( warnings.warn(
"The `%s` GET parameter has been renamed to `%s`." % "The `%s` GET parameter has been renamed to `%s`." %
(IS_LEGACY_POPUP_VAR, IS_POPUP_VAR), (IS_LEGACY_POPUP_VAR, IS_POPUP_VAR),
PendingDeprecationWarning, 2) DeprecationWarning, 2)
return True return True
return False return False
@ -60,7 +60,7 @@ def _is_changelist_popup(request):
class RenameChangeListMethods(RenameMethodsBase): class RenameChangeListMethods(RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning), ('get_query_set', 'get_queryset', DeprecationWarning),
) )
@ -115,14 +115,14 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)):
def root_query_set(self): def root_query_set(self):
warnings.warn("`ChangeList.root_query_set` is deprecated, " warnings.warn("`ChangeList.root_query_set` is deprecated, "
"use `root_queryset` instead.", "use `root_queryset` instead.",
PendingDeprecationWarning, 2) DeprecationWarning, 2)
return self.root_queryset return self.root_queryset
@property @property
def query_set(self): def query_set(self):
warnings.warn("`ChangeList.query_set` is deprecated, " warnings.warn("`ChangeList.query_set` is deprecated, "
"use `queryset` instead.", "use `queryset` instead.",
PendingDeprecationWarning, 2) DeprecationWarning, 2)
return self.queryset return self.queryset
def get_filters_params(self, params=None): def get_filters_params(self, params=None):

View File

@ -1,9 +1,10 @@
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
import unittest
from django.contrib.admindocs import views from django.contrib.admindocs import views
from django.db import models from django.db import models
from django.db.models import fields from django.db.models import fields
from django.utils import unittest
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _

View File

@ -1,7 +1,5 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django import forms from django import forms
from django.forms.util import flatatt from django.forms.util import flatatt
from django.template import loader from django.template import loader
@ -200,10 +198,6 @@ class AuthenticationForm(forms.Form):
) )
return self.cleaned_data return self.cleaned_data
def check_for_test_cookie(self):
warnings.warn("check_for_test_cookie is deprecated; ensure your login "
"view is CSRF-protected.", DeprecationWarning)
def get_user_id(self): def get_user_id(self):
if self.user_cache: if self.user_cache:
return self.user_cache.id return self.user_cache.id

View File

@ -1,8 +1,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import re import re
import warnings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import send_mail from django.core.mail import send_mail
from django.core import validators from django.core import validators
from django.db import models from django.db import models
@ -14,7 +12,6 @@ from django.utils.translation import ugettext_lazy as _
from django.utils import timezone from django.utils import timezone
from django.contrib import auth from django.contrib import auth
# UNUSABLE_PASSWORD is still imported here for backwards compatibility
from django.contrib.auth.hashers import ( from django.contrib.auth.hashers import (
check_password, make_password, is_password_usable) check_password, make_password, is_password_usable)
from django.contrib.auth.signals import user_logged_in from django.contrib.auth.signals import user_logged_in
@ -32,10 +29,6 @@ def update_last_login(sender, user, **kwargs):
user_logged_in.connect(update_last_login) user_logged_in.connect(update_last_login)
class SiteProfileNotAvailable(Exception):
pass
class PermissionManager(models.Manager): class PermissionManager(models.Manager):
def get_by_natural_key(self, codename, app_label, model): def get_by_natural_key(self, codename, app_label, model):
return self.get( return self.get(
@ -413,38 +406,6 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin):
""" """
send_mail(subject, message, from_email, [self.email]) send_mail(subject, message, from_email, [self.email])
def get_profile(self):
"""
Returns site-specific profile for this user. Raises
SiteProfileNotAvailable if this site does not allow profiles.
"""
warnings.warn("The use of AUTH_PROFILE_MODULE to define user profiles has been deprecated.",
DeprecationWarning, stacklevel=2)
if not hasattr(self, '_profile_cache'):
from django.conf import settings
if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
raise SiteProfileNotAvailable(
'You need to set AUTH_PROFILE_MODULE in your project '
'settings')
try:
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
except ValueError:
raise SiteProfileNotAvailable(
'app_label and model_name should be separated by a dot in '
'the AUTH_PROFILE_MODULE setting')
try:
model = models.get_model(app_label, model_name)
if model is None:
raise SiteProfileNotAvailable(
'Unable to load the profile model, check '
'AUTH_PROFILE_MODULE in your project settings')
self._profile_cache = model._default_manager.using(
self._state.db).get(user__id__exact=self.id)
self._profile_cache.user = self
except (ImportError, ImproperlyConfigured):
raise SiteProfileNotAvailable
return self._profile_cache
class User(AbstractUser): class User(AbstractUser):
""" """

View File

@ -1,13 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import unittest
from unittest import skipUnless
from django.conf.global_settings import PASSWORD_HASHERS as default_hashers from django.conf.global_settings import PASSWORD_HASHERS as default_hashers
from django.contrib.auth.hashers import (is_password_usable, BasePasswordHasher, from django.contrib.auth.hashers import (is_password_usable, BasePasswordHasher,
check_password, make_password, PBKDF2PasswordHasher, load_hashers, PBKDF2SHA1PasswordHasher, check_password, make_password, PBKDF2PasswordHasher, load_hashers, PBKDF2SHA1PasswordHasher,
get_hasher, identify_hasher, UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH) get_hasher, identify_hasher, UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH)
from django.utils import six from django.utils import six
from django.utils import unittest
from django.utils.unittest import skipUnless
try: try:

View File

@ -1,46 +1,9 @@
import warnings
from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.models import (Group, User, SiteProfileNotAvailable, from django.contrib.auth.models import Group, User, UserManager
UserManager)
from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.auth.tests.utils import skipIfCustomUser
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six
@skipIfCustomUser
@override_settings(USE_TZ=False, AUTH_PROFILE_MODULE='')
class ProfileTestCase(TestCase):
def test_site_profile_not_available(self):
user = User.objects.create(username='testclient')
# calling get_profile without AUTH_PROFILE_MODULE set
del settings.AUTH_PROFILE_MODULE
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"You need to set AUTH_PROFILE_MODULE in your project"):
user.get_profile()
# Bad syntax in AUTH_PROFILE_MODULE:
settings.AUTH_PROFILE_MODULE = 'foobar'
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"app_label and model_name should be separated by a dot"):
user.get_profile()
# module that doesn't exist
settings.AUTH_PROFILE_MODULE = 'foo.bar'
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"Unable to load the profile model"):
user.get_profile()
@skipIfCustomUser @skipIfCustomUser

View File

@ -1,12 +1,12 @@
import sys
from datetime import date, timedelta from datetime import date, timedelta
import sys
import unittest
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.auth.tests.utils import skipIfCustomUser
from django.test import TestCase from django.test import TestCase
from django.utils import unittest
@skipIfCustomUser @skipIfCustomUser

View File

@ -13,7 +13,7 @@ from django.core import mail
from django.core.urlresolvers import reverse, NoReverseMatch from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import QueryDict, HttpRequest from django.http import QueryDict, HttpRequest
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.http import int_to_base36, urlsafe_base64_decode, urlquote from django.utils.http import urlquote
from django.utils._os import upath from django.utils._os import upath
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings, patch_logger from django.test.utils import override_settings, patch_logger
@ -193,16 +193,6 @@ class PasswordResetTest(AuthViewsTestCase):
# redirect to a 'complete' page: # redirect to a 'complete' page:
self.assertContains(response, "Please enter your new password") self.assertContains(response, "Please enter your new password")
def test_confirm_valid_base36(self):
# Remove in Django 1.7
url, path = self._test_confirm_start()
path_parts = path.strip("/").split("/")
# construct an old style (base36) URL by converting the base64 ID
path_parts[1] = int_to_base36(int(urlsafe_base64_decode(path_parts[1])))
response = self.client.get("/%s/%s-%s/" % tuple(path_parts))
# redirect to a 'complete' page:
self.assertContains(response, "Please enter your new password")
def test_confirm_invalid(self): def test_confirm_invalid(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
# Let's munge the token in the path, but keep the same length, # Let's munge the token in the path, but keep the same length,
@ -217,21 +207,11 @@ class PasswordResetTest(AuthViewsTestCase):
response = self.client.get('/reset/123456/1-1/') response = self.client.get('/reset/123456/1-1/')
self.assertContains(response, "The password reset link was invalid") self.assertContains(response, "The password reset link was invalid")
def test_confirm_invalid_user_base36(self):
# Remove in Django 1.7
response = self.client.get('/reset/123456-1-1/')
self.assertContains(response, "The password reset link was invalid")
def test_confirm_overflow_user(self): def test_confirm_overflow_user(self):
# Ensure that we get a 200 response for a base36 user id that overflows int # Ensure that we get a 200 response for a base36 user id that overflows int
response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/')
self.assertContains(response, "The password reset link was invalid") self.assertContains(response, "The password reset link was invalid")
def test_confirm_overflow_user_base36(self):
# Remove in Django 1.7
response = self.client.get('/reset/zzzzzzzzzzzzz-1-1/')
self.assertContains(response, "The password reset link was invalid")
def test_confirm_invalid_post(self): def test_confirm_invalid_post(self):
# Same as test_confirm_invalid, but trying # Same as test_confirm_invalid, but trying
# to do a POST instead. # to do a POST instead.

View File

@ -1,5 +1,6 @@
from unittest import skipIf
from django.conf import settings from django.conf import settings
from django.utils.unittest import skipIf
def skipIfCustomUser(test_func): def skipIfCustomUser(test_func):

View File

@ -12,9 +12,6 @@ urlpatterns = patterns('',
url(r'^password_change/done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'), url(r'^password_change/done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'),
url(r'^password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'), url(r'^password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'),
url(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), url(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'),
# Support old style base36 password reset links; remove in Django 1.7
url(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
'django.contrib.auth.views.password_reset_confirm_uidb36'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
'django.contrib.auth.views.password_reset_confirm', 'django.contrib.auth.views.password_reset_confirm',
name='password_reset_confirm'), name='password_reset_confirm'),

View File

@ -228,15 +228,6 @@ def password_reset_confirm(request, uidb64=None, token=None,
return TemplateResponse(request, template_name, context, return TemplateResponse(request, template_name, context,
current_app=current_app) current_app=current_app)
def password_reset_confirm_uidb36(request, uidb36=None, **kwargs):
# Support old password reset URLs that used base36 encoded user IDs.
# Remove in Django 1.7
try:
uidb64 = force_text(urlsafe_base64_encode(force_bytes(base36_to_int(uidb36))))
except ValueError:
uidb64 = '1' # dummy invalid ID (incorrect padding for base64)
return password_reset_confirm(request, uidb64=uidb64, **kwargs)
def password_reset_complete(request, def password_reset_complete(request,
template_name='registration/password_reset_complete.html', template_name='registration/password_reset_complete.html',
current_app=None, extra_context=None): current_app=None, extra_context=None):

View File

@ -6,7 +6,7 @@ from django.contrib.comments.models import Comment
from django.contrib.comments.forms import CommentForm from django.contrib.comments.forms import CommentForm
from django.utils.importlib import import_module from django.utils.importlib import import_module
warnings.warn("django.contrib.comments is deprecated and will be removed before Django 1.8.", PendingDeprecationWarning) warnings.warn("django.contrib.comments is deprecated and will be removed before Django 1.8.", DeprecationWarning)
DEFAULT_COMMENTS_APP = 'django.contrib.comments' DEFAULT_COMMENTS_APP = 'django.contrib.comments'

View File

@ -12,7 +12,7 @@ register = template.Library()
class RenameBaseCommentNodeMethods(RenameMethodsBase): class RenameBaseCommentNodeMethods(RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning), ('get_query_set', 'get_queryset', DeprecationWarning),
) )

View File

@ -25,7 +25,7 @@ from django.utils.encoding import smart_text
class RenameGenericForeignKeyMethods(RenameMethodsBase): class RenameGenericForeignKeyMethods(RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('get_prefetch_query_set', 'get_prefetch_queryset', PendingDeprecationWarning), ('get_prefetch_query_set', 'get_prefetch_queryset', DeprecationWarning),
) )
@ -434,8 +434,8 @@ def generic_inlineformset_factory(model, form=ModelForm,
""" """
Returns a ``GenericInlineFormSet`` for the given kwargs. Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``object_id`` if they different from the You must provide ``ct_field`` and ``fk_field`` if they are different from
defaults ``content_type`` and ``object_id`` respectively. the defaults ``content_type`` and ``object_id`` respectively.
""" """
opts = model._meta opts = model._meta
# if there is no field called `ct_field` let the exception propagate # if there is no field called `ct_field` let the exception propagate

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
import datetime import datetime
import os import os
import unittest
import warnings import warnings
from django import http from django import http
@ -10,7 +11,6 @@ from django.contrib.formtools import preview, utils
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils._os import upath from django.utils._os import upath
from django.utils import unittest
from django.contrib.formtools.tests.forms import * from django.contrib.formtools.tests.forms import *

View File

@ -1,7 +1,5 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django import forms from django import forms
from django.utils import six from django.utils import six
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -34,10 +32,6 @@ class GeometryField(forms.Field):
# defaults (e.g., allow None). # defaults (e.g., allow None).
self.srid = kwargs.pop('srid', None) self.srid = kwargs.pop('srid', None)
self.geom_type = kwargs.pop('geom_type', self.geom_type) self.geom_type = kwargs.pop('geom_type', self.geom_type)
if 'null' in kwargs:
kwargs.pop('null', True)
warnings.warn("Passing 'null' keyword argument to GeometryField is deprecated.",
DeprecationWarning, stacklevel=2)
super(GeometryField, self).__init__(**kwargs) super(GeometryField, self).__init__(**kwargs)
self.widget.attrs['geom_type'] = self.geom_type self.widget.attrs['geom_type'] = self.geom_type

View File

@ -1,6 +1,7 @@
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.utils import unittest
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Driver, OGRException from django.contrib.gis.gdal import Driver, OGRException

View File

@ -1,9 +1,9 @@
import os import os
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA
from django.utils import unittest
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError, GDAL_VERSION from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError, GDAL_VERSION

View File

@ -1,6 +1,7 @@
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.utils import unittest
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Envelope, OGRException from django.contrib.gis.gdal import Envelope, OGRException

View File

@ -4,12 +4,12 @@ try:
from django.utils.six.moves import cPickle as pickle from django.utils.six.moves import cPickle as pickle
except ImportError: except ImportError:
import pickle import pickle
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geometry.test_data import TestDataMixin from django.contrib.gis.geometry.test_data import TestDataMixin
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
from django.utils import unittest
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType, from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType,

View File

@ -1,6 +1,7 @@
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.utils import unittest
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import SpatialReference, CoordTransform, OGRException, SRSException from django.contrib.gis.gdal import SpatialReference, CoordTransform, OGRException, SRSException

View File

@ -2,11 +2,12 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import os import os
import unittest
from unittest import skipUnless
from django.conf import settings from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.geoip import HAS_GEOIP from django.contrib.gis.geoip import HAS_GEOIP
from django.utils import unittest
from django.utils.unittest import skipUnless
from django.utils import six from django.utils import six

View File

@ -3,6 +3,8 @@ from __future__ import unicode_literals
import ctypes import ctypes
import json import json
import random import random
import unittest
from unittest import skipUnless
from binascii import a2b_hex, b2a_hex from binascii import a2b_hex, b2a_hex
from io import BytesIO from io import BytesIO
@ -14,8 +16,6 @@ from django.contrib.gis.geometry.test_data import TestDataMixin
from django.utils.encoding import force_bytes from django.utils.encoding import force_bytes
from django.utils import six from django.utils import six
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
from django.utils import unittest
from django.utils.unittest import skipUnless
from .. import HAS_GEOS from .. import HAS_GEOS

View File

@ -2,8 +2,8 @@
# Modified from original contribution by Aryeh Leib Taurog, which was # Modified from original contribution by Aryeh Leib Taurog, which was
# released under the New BSD license. # released under the New BSD license.
from django.utils import unittest import unittest
from django.utils.unittest import skipUnless from unittest import skipUnless
from .. import HAS_GEOS from .. import HAS_GEOS

View File

@ -2,9 +2,9 @@ from __future__ import unicode_literals
import binascii import binascii
import unittest import unittest
from unittest import skipUnless
from django.contrib.gis import memoryview from django.contrib.gis import memoryview
from django.utils.unittest import skipUnless
from ..import HAS_GEOS from ..import HAS_GEOS

View File

@ -3,9 +3,11 @@
# #
# Modified from original contribution by Aryeh Leib Taurog, which was # Modified from original contribution by Aryeh Leib Taurog, which was
# released under the New BSD license. # released under the New BSD license.
import unittest
from django.contrib.gis.geos.mutable_list import ListMixin from django.contrib.gis.geos.mutable_list import ListMixin
from django.utils import six from django.utils import six
from django.utils import unittest
class UserListA(ListMixin): class UserListA(ListMixin):

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from unittest import skipUnless
from django.db import connection from django.db import connection
from django.db.models import Q from django.db.models import Q
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
@ -8,7 +10,6 @@ from django.contrib.gis.tests.utils import (
HAS_SPATIAL_DB, mysql, oracle, postgis, spatialite, no_oracle, no_spatialite HAS_SPATIAL_DB, mysql, oracle, postgis, spatialite, no_oracle, no_spatialite
) )
from django.test import TestCase from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS and HAS_SPATIAL_DB: if HAS_GEOS and HAS_SPATIAL_DB:
from django.contrib.gis.geos import GEOSGeometry, LineString from django.contrib.gis.geos import GEOSGeometry, LineString

View File

@ -2,13 +2,13 @@ from __future__ import absolute_import, unicode_literals
import os import os
import re import re
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import postgis from django.contrib.gis.tests.utils import postgis
from django.test import TestCase from django.test import TestCase
from django.utils._os import upath from django.utils._os import upath
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from django.contrib.gis.db.models import Union, Extent3D from django.contrib.gis.db.models import Union, Extent3D

View File

@ -1,9 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from unittest import skipUnless
from django.test import TestCase from django.test import TestCase
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.utils.unittest import skipUnless
if HAS_GEOS and HAS_SPATIAL_DB: if HAS_GEOS and HAS_SPATIAL_DB:
from django.contrib.gis import admin from django.contrib.gis import admin

View File

@ -1,5 +1,6 @@
from __future__ import absolute_import from __future__ import absolute_import
from unittest import skipUnless
from xml.dom import minidom from xml.dom import minidom
from django.conf import settings from django.conf import settings
@ -7,7 +8,6 @@ from django.contrib.sites.models import Site
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.test import TestCase from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from .models import City from .models import City

View File

@ -2,6 +2,7 @@
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
from datetime import datetime from datetime import datetime
from unittest import skipUnless
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import no_mysql, no_spatialite from django.contrib.gis.tests.utils import no_mysql, no_spatialite
@ -9,7 +10,6 @@ from django.contrib.gis.shortcuts import render_to_kmz
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.db.models import Count, Min from django.db.models import Count, Min
from django.test import TestCase from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from .models import City, PennsylvaniaCity, State, Truth from .models import City, PennsylvaniaCity, State, Truth

View File

@ -1,6 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from io import BytesIO from io import BytesIO
from unittest import skipUnless
from xml.dom import minidom from xml.dom import minidom
import zipfile import zipfile
@ -9,7 +10,6 @@ from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.test import TestCase from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from .models import City, Country from .models import City, Country

View File

@ -1,6 +1,8 @@
from __future__ import absolute_import from __future__ import absolute_import
import re import re
import unittest
from unittest import skipUnless
from django.db import connection from django.db import connection
from django.contrib.gis import gdal from django.contrib.gis import gdal
@ -9,8 +11,7 @@ from django.contrib.gis.tests.utils import (
no_mysql, no_oracle, no_spatialite, no_mysql, no_oracle, no_spatialite,
mysql, oracle, postgis, spatialite) mysql, oracle, postgis, spatialite)
from django.test import TestCase from django.test import TestCase
from django.utils import six, unittest from django.utils import six
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from django.contrib.gis.geos import (fromstr, GEOSGeometry, from django.contrib.gis.geos import (fromstr, GEOSGeometry,

View File

@ -4,6 +4,7 @@ Tests for geography support in PostGIS 1.5+
from __future__ import absolute_import from __future__ import absolute_import
import os import os
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
@ -11,7 +12,6 @@ from django.contrib.gis.measure import D
from django.contrib.gis.tests.utils import postgis from django.contrib.gis.tests.utils import postgis
from django.test import TestCase from django.test import TestCase
from django.utils._os import upath from django.utils._os import upath
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from .models import City, County, Zipcode from .models import City, County, Zipcode

View File

@ -1,13 +1,13 @@
from __future__ import absolute_import from __future__ import absolute_import
import os import os
from unittest import skipUnless
from django.db import connections from django.db import connections
from django.test import TestCase from django.test import TestCase
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geometry.test_data import TEST_DATA from django.contrib.gis.geometry.test_data import TEST_DATA
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.utils.unittest import skipUnless
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Driver from django.contrib.gis.gdal import Driver

View File

@ -1,17 +1,17 @@
# coding: utf-8 # coding: utf-8
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
import os
from copy import copy from copy import copy
from decimal import Decimal from decimal import Decimal
import os
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB, mysql from django.contrib.gis.tests.utils import HAS_SPATIAL_DB, mysql
from django.db import router from django.db import router
from django.conf import settings from django.conf import settings
from django.test import TestCase from django.test import TestCase
from django.utils import unittest
from django.utils.unittest import skipUnless
from django.utils._os import upath from django.utils._os import upath
if HAS_GDAL: if HAS_GDAL:

View File

@ -1,9 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from unittest import skipUnless
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB, mysql, oracle, no_mysql, no_oracle, no_spatialite from django.contrib.gis.tests.utils import HAS_SPATIAL_DB, mysql, oracle, no_mysql, no_oracle, no_spatialite
from django.test import TestCase from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS: if HAS_GEOS:
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.db.models import Collect, Count, Extent, F, Union

View File

@ -1,15 +1,16 @@
from unittest import skipUnless
from django.forms import ValidationError from django.forms import ValidationError
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.tests.utils import HAS_SPATIALREFSYS from django.contrib.gis.tests.utils import HAS_SPATIALREFSYS
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.utils import six from django.utils import six
from django.utils.unittest import skipUnless
if HAS_SPATIALREFSYS: if HAS_SPATIALREFSYS:
from django.contrib.gis import forms from django.contrib.gis import forms
from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos import GEOSGeometry
@skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "GeometryFieldTest needs gdal support and a spatial database") @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "GeometryFieldTest needs gdal support and a spatial database")
class GeometryFieldTest(SimpleTestCase): class GeometryFieldTest(SimpleTestCase):

View File

@ -3,8 +3,9 @@ Distance and Area objects to allow for sensible and convienient calculation
and conversions. Here are some tests. and conversions. Here are some tests.
""" """
import unittest
from django.contrib.gis.measure import Distance, Area, D, A from django.contrib.gis.measure import Distance, Area, D, A
from django.utils import unittest
class DistanceTest(unittest.TestCase): class DistanceTest(unittest.TestCase):

View File

@ -1,8 +1,9 @@
import unittest
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.tests.utils import (no_mysql, oracle, postgis, from django.contrib.gis.tests.utils import (no_mysql, oracle, postgis,
spatialite, HAS_SPATIALREFSYS, SpatialRefSys) spatialite, HAS_SPATIALREFSYS, SpatialRefSys)
from django.utils import six from django.utils import six
from django.utils import unittest
test_srs = ({'srid' : 4326, test_srs = ({'srid' : 4326,

View File

@ -1,6 +1,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import datetime import datetime
from decimal import Decimal from decimal import Decimal
from unittest import skipIf
try: try:
import pytz import pytz
@ -17,7 +18,6 @@ from django.utils.timezone import utc
from django.utils import translation from django.utils import translation
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.utils import tzinfo from django.utils import tzinfo
from django.utils.unittest import skipIf
from i18n import TransRealMixin from i18n import TransRealMixin

View File

@ -1,3 +1,5 @@
from unittest import skipIf
from django import http from django import http
from django.conf import settings, global_settings from django.conf import settings, global_settings
from django.contrib.messages import constants, utils, get_level, set_level from django.contrib.messages import constants, utils, get_level, set_level
@ -7,7 +9,6 @@ from django.contrib.messages.storage.base import Message
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils.translation import ugettext_lazy from django.utils.translation import ugettext_lazy
from django.utils.unittest import skipIf
def skipUnlessAuthIsInstalled(func): def skipUnlessAuthIsInstalled(func):

View File

@ -1,6 +1,7 @@
import unittest
from django import http from django import http
from django.contrib.messages.middleware import MessageMiddleware from django.contrib.messages.middleware import MessageMiddleware
from django.utils import unittest
class MiddlewareTest(unittest.TestCase): class MiddlewareTest(unittest.TestCase):

View File

@ -6,10 +6,13 @@ from django.utils.http import cookie_date
from django.utils.importlib import import_module from django.utils.importlib import import_module
class SessionMiddleware(object): class SessionMiddleware(object):
def process_request(self, request): def __init__(self):
engine = import_module(settings.SESSION_ENGINE) engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
def process_request(self, request):
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
request.session = engine.SessionStore(session_key) request.session = self.SessionStore(session_key)
def process_response(self, request, response): def process_response(self, request, response):
""" """

View File

@ -4,6 +4,7 @@ import os
import shutil import shutil
import string import string
import tempfile import tempfile
import unittest
import warnings import warnings
from django.conf import settings from django.conf import settings
@ -22,7 +23,6 @@ from django.test import TestCase, RequestFactory
from django.test.utils import override_settings, patch_logger from django.test.utils import override_settings, patch_logger
from django.utils import six from django.utils import six
from django.utils import timezone from django.utils import timezone
from django.utils import unittest
from django.contrib.sessions.exceptions import InvalidSessionKey from django.contrib.sessions.exceptions import InvalidSessionKey

View File

@ -1,7 +1,8 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from unittest import skipUnless
from django.conf import settings from django.conf import settings
from django.utils.unittest import skipUnless
from .base import SitemapTestsBase from .base import SitemapTestsBase

View File

@ -2,13 +2,13 @@ from __future__ import unicode_literals
import os import os
from datetime import date from datetime import date
from unittest import skipUnless
from django.conf import settings from django.conf import settings
from django.contrib.sitemaps import Sitemap, GenericSitemap from django.contrib.sitemaps import Sitemap, GenericSitemap
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils.unittest import skipUnless
from django.utils.formats import localize from django.utils.formats import localize
from django.utils._os import upath from django.utils._os import upath
from django.utils.translation import activate, deactivate from django.utils.translation import activate, deactivate

View File

@ -1,4 +1,3 @@
import warnings
from functools import wraps from functools import wraps
from django.contrib.sites.models import get_current_site from django.contrib.sites.models import get_current_site
@ -19,13 +18,7 @@ def x_robots_tag(func):
@x_robots_tag @x_robots_tag
def index(request, sitemaps, def index(request, sitemaps,
template_name='sitemap_index.xml', content_type='application/xml', template_name='sitemap_index.xml', content_type='application/xml',
sitemap_url_name='django.contrib.sitemaps.views.sitemap', sitemap_url_name='django.contrib.sitemaps.views.sitemap'):
mimetype=None):
if mimetype:
warnings.warn("The mimetype keyword argument is deprecated, use "
"content_type instead", DeprecationWarning, stacklevel=2)
content_type = mimetype
req_protocol = 'https' if request.is_secure() else 'http' req_protocol = 'https' if request.is_secure() else 'http'
req_site = get_current_site(request) req_site = get_current_site(request)
@ -47,13 +40,7 @@ def index(request, sitemaps,
@x_robots_tag @x_robots_tag
def sitemap(request, sitemaps, section=None, def sitemap(request, sitemaps, section=None,
template_name='sitemap.xml', content_type='application/xml', template_name='sitemap.xml', content_type='application/xml'):
mimetype=None):
if mimetype:
warnings.warn("The mimetype keyword argument is deprecated, use "
"content_type instead", DeprecationWarning, stacklevel=2)
content_type = mimetype
req_protocol = 'https' if request.is_secure() else 'http' req_protocol = 'https' if request.is_secure() else 'http'
req_site = get_current_site(request) req_site = get_current_site(request)

View File

@ -231,6 +231,7 @@ class FileSystemStorage(Storage):
return name return name
def delete(self, name): def delete(self, name):
assert name, "The name argument is not allowed to be empty."
name = self.path(name) name = self.path(name)
# If the file exists, delete it from the filesystem. # If the file exists, delete it from the filesystem.
# Note that there is a race between os.path.exists and os.remove: # Note that there is a race between os.path.exists and os.remove:

View File

@ -1,11 +0,0 @@
import warnings
from django.contrib.sessions.management.commands import clearsessions
class Command(clearsessions.Command):
def handle_noargs(self, **options):
warnings.warn(
"The `cleanup` command has been deprecated in favor of `clearsessions`.",
DeprecationWarning)
super(Command, self).handle_noargs(**options)

View File

@ -49,7 +49,7 @@ class DefaultBackendProxy(object):
@cached_property @cached_property
def _backend(self): def _backend(self):
warnings.warn("Accessing django.db.backend is deprecated.", warnings.warn("Accessing django.db.backend is deprecated.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
return load_backend(connections[DEFAULT_DB_ALIAS].settings_dict['ENGINE']) return load_backend(connections[DEFAULT_DB_ALIAS].settings_dict['ENGINE'])
def __getattr__(self, item): def __getattr__(self, item):
@ -66,7 +66,7 @@ backend = DefaultBackendProxy()
def close_connection(**kwargs): def close_connection(**kwargs):
warnings.warn( warnings.warn(
"close_connection is superseded by close_old_connections.", "close_connection is superseded by close_old_connections.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
# Avoid circular imports # Avoid circular imports
from django.db import transaction from django.db import transaction
for conn in connections: for conn in connections:

View File

@ -204,7 +204,7 @@ class BaseDatabaseWrapper(object):
def _savepoint_allowed(self): def _savepoint_allowed(self):
# Savepoints cannot be created outside a transaction # Savepoints cannot be created outside a transaction
return self.features.uses_savepoints and not self.autocommit return self.features.uses_savepoints and not self.get_autocommit()
##### Generic savepoint management methods ##### ##### Generic savepoint management methods #####
@ -279,15 +279,13 @@ class BaseDatabaseWrapper(object):
""" """
self.validate_no_atomic_block() self.validate_no_atomic_block()
self.ensure_connection()
self.transaction_state.append(managed) self.transaction_state.append(managed)
if not managed and self.is_dirty() and not forced: if not managed and self.is_dirty() and not forced:
self.commit() self.commit()
self.set_clean() self.set_clean()
if managed == self.autocommit: if managed == self.get_autocommit():
self.set_autocommit(not managed) self.set_autocommit(not managed)
def leave_transaction_management(self): def leave_transaction_management(self):
@ -298,8 +296,6 @@ class BaseDatabaseWrapper(object):
""" """
self.validate_no_atomic_block() self.validate_no_atomic_block()
self.ensure_connection()
if self.transaction_state: if self.transaction_state:
del self.transaction_state[-1] del self.transaction_state[-1]
else: else:
@ -313,14 +309,21 @@ class BaseDatabaseWrapper(object):
if self._dirty: if self._dirty:
self.rollback() self.rollback()
if managed == self.autocommit: if managed == self.get_autocommit():
self.set_autocommit(not managed) self.set_autocommit(not managed)
raise TransactionManagementError( raise TransactionManagementError(
"Transaction managed block ended with pending COMMIT/ROLLBACK") "Transaction managed block ended with pending COMMIT/ROLLBACK")
if managed == self.autocommit: if managed == self.get_autocommit():
self.set_autocommit(not managed) self.set_autocommit(not managed)
def get_autocommit(self):
"""
Check the autocommit state.
"""
self.ensure_connection()
return self.autocommit
def set_autocommit(self, autocommit): def set_autocommit(self, autocommit):
""" """
Enable or disable autocommit. Enable or disable autocommit.
@ -330,13 +333,22 @@ class BaseDatabaseWrapper(object):
self._set_autocommit(autocommit) self._set_autocommit(autocommit)
self.autocommit = autocommit self.autocommit = autocommit
def get_rollback(self):
"""
Get the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
return self.needs_rollback
def set_rollback(self, rollback): def set_rollback(self, rollback):
""" """
Set or unset the "needs rollback" flag -- for *advanced use* only. Set or unset the "needs rollback" flag -- for *advanced use* only.
""" """
if not self.in_atomic_block: if not self.in_atomic_block:
raise TransactionManagementError( raise TransactionManagementError(
"needs_rollback doesn't work outside of an 'atomic' block.") "The rollback flag doesn't work outside of an 'atomic' block.")
self.needs_rollback = rollback self.needs_rollback = rollback
def validate_no_atomic_block(self): def validate_no_atomic_block(self):
@ -370,7 +382,7 @@ class BaseDatabaseWrapper(object):
to decide in a managed block of code to decide whether there are open to decide in a managed block of code to decide whether there are open
changes waiting for commit. changes waiting for commit.
""" """
if not self.autocommit: if not self.get_autocommit():
self._dirty = True self._dirty = True
def set_clean(self): def set_clean(self):
@ -436,7 +448,7 @@ class BaseDatabaseWrapper(object):
if self.connection is not None: if self.connection is not None:
# If the application didn't restore the original autocommit setting, # If the application didn't restore the original autocommit setting,
# don't take chances, drop the connection. # don't take chances, drop the connection.
if self.autocommit != self.settings_dict['AUTOCOMMIT']: if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
self.close() self.close()
return return

View File

@ -468,7 +468,7 @@ class BaseDatabaseCreation(object):
""" """
warnings.warn( warnings.warn(
"set_autocommit was moved from BaseDatabaseCreation to " "set_autocommit was moved from BaseDatabaseCreation to "
"BaseDatabaseWrapper.", PendingDeprecationWarning, stacklevel=2) "BaseDatabaseWrapper.", DeprecationWarning, stacklevel=2)
return self.connection.set_autocommit(True) return self.connection.set_autocommit(True)
def sql_table_creation_suffix(self): def sql_table_creation_suffix(self):

View File

@ -288,7 +288,7 @@ class DatabaseOperations(BaseDatabaseOperations):
# With MySQLdb, cursor objects have an (undocumented) "_last_executed" # With MySQLdb, cursor objects have an (undocumented) "_last_executed"
# attribute where the exact query sent to the database is saved. # attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution. # See MySQLdb/cursors.py in the source distribution.
return force_text(cursor._last_executed, errors='replace') return force_text(getattr(cursor, '_last_executed', None), errors='replace')
def no_limit_value(self): def no_limit_value(self):
# 2**64 - 1, as recommended by the MySQL documentation # 2**64 - 1, as recommended by the MySQL documentation

View File

@ -79,14 +79,8 @@ Database.register_converter(str("decimal"), decoder(util.typecast_decimal))
Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support) Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support)
Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal)
if Database.version_info >= (2, 4, 1): Database.register_adapter(str, lambda s: s.decode('utf-8'))
# Starting in 2.4.1, the str type is not accepted anymore, therefore, Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8'))
# we convert all str objects to Unicode
# As registering a adapter for a primitive type causes a small
# slow-down, this adapter is only registered for sqlite3 versions
# needing it (Python 2.6 and up).
Database.register_adapter(str, lambda s: s.decode('utf-8'))
Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8'))
class DatabaseFeatures(BaseDatabaseFeatures): class DatabaseFeatures(BaseDatabaseFeatures):
# SQLite cannot handle us only partially reading from a cursor's result set # SQLite cannot handle us only partially reading from a cursor's result set

View File

@ -96,6 +96,8 @@ class FieldFile(File):
save.alters_data = True save.alters_data = True
def delete(self, save=True): def delete(self, save=True):
if not self:
return
# Only close the file if it's already open, which we know by the # Only close the file if it's already open, which we know by the
# presence of self._file # presence of self._file
if hasattr(self, '_file'): if hasattr(self, '_file'):

View File

@ -89,7 +89,6 @@ def do_pending_lookups(sender, **kwargs):
signals.class_prepared.connect(do_pending_lookups) signals.class_prepared.connect(do_pending_lookups)
#HACK
class RelatedField(Field): class RelatedField(Field):
def db_type(self, connection): def db_type(self, connection):
'''By default related field will not have a column '''By default related field will not have a column
@ -142,8 +141,8 @@ class RelatedField(Field):
class RenameRelatedObjectDescriptorMethods(RenameMethodsBase): class RenameRelatedObjectDescriptorMethods(RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning), ('get_query_set', 'get_queryset', DeprecationWarning),
('get_prefetch_query_set', 'get_prefetch_queryset', PendingDeprecationWarning), ('get_prefetch_query_set', 'get_prefetch_queryset', DeprecationWarning),
) )
@ -1166,7 +1165,7 @@ class ForeignKey(ForeignObject):
rel = self.rel rel = self.rel
if self.rel.field_name: if self.rel.field_name:
kwargs['to_field'] = self.rel.field_name kwargs['to_field'] = self.rel.field_name
if isinstance(self.rel.to, basestring): if isinstance(self.rel.to, six.string_types):
kwargs['to'] = self.rel.to kwargs['to'] = self.rel.to
else: else:
kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name) kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
@ -1367,9 +1366,7 @@ class ManyToManyField(RelatedField):
assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name)
except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
# Python 2.6 and earlier require dictionary keys to be of str type, # Class names must be ASCII in Python 2.x, so we forcibly coerce it here to break early if there's a problem.
# not unicode and class names must be ASCII (in Python 2.x), so we
# forcibly coerce it here (breaks early if there's a problem).
to = str(to) to = str(to)
kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['verbose_name'] = kwargs.get('verbose_name', None)
@ -1397,7 +1394,7 @@ class ManyToManyField(RelatedField):
del kwargs['help_text'] del kwargs['help_text']
# Rel needs more work. # Rel needs more work.
rel = self.rel rel = self.rel
if isinstance(self.rel.to, basestring): if isinstance(self.rel.to, six.string_types):
kwargs['to'] = self.rel.to kwargs['to'] = self.rel.to
else: else:
kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name) kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)

View File

@ -50,8 +50,8 @@ signals.class_prepared.connect(ensure_default_manager)
class RenameManagerMethods(RenameMethodsBase): class RenameManagerMethods(RenameMethodsBase):
renamed_methods = ( renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning), ('get_query_set', 'get_queryset', DeprecationWarning),
('get_prefetch_query_set', 'get_prefetch_queryset', PendingDeprecationWarning), ('get_prefetch_query_set', 'get_prefetch_queryset', DeprecationWarning),
) )

View File

@ -138,7 +138,7 @@ class Options(object):
""" """
warnings.warn( warnings.warn(
"Options.module_name has been deprecated in favor of model_name", "Options.module_name has been deprecated in favor of model_name",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
return self.model_name return self.model_name
def _prepare(self, model): def _prepare(self, model):
@ -429,7 +429,7 @@ class Options(object):
warnings.warn( warnings.warn(
"`Options.get_add_permission` has been deprecated in favor " "`Options.get_add_permission` has been deprecated in favor "
"of `django.contrib.auth.get_permission_codename`.", "of `django.contrib.auth.get_permission_codename`.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
return 'add_%s' % self.model_name return 'add_%s' % self.model_name
def get_change_permission(self): def get_change_permission(self):
@ -440,7 +440,7 @@ class Options(object):
warnings.warn( warnings.warn(
"`Options.get_change_permission` has been deprecated in favor " "`Options.get_change_permission` has been deprecated in favor "
"of `django.contrib.auth.get_permission_codename`.", "of `django.contrib.auth.get_permission_codename`.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
return 'change_%s' % self.model_name return 'change_%s' % self.model_name
def get_delete_permission(self): def get_delete_permission(self):
@ -451,7 +451,7 @@ class Options(object):
warnings.warn( warnings.warn(
"`Options.get_delete_permission` has been deprecated in favor " "`Options.get_delete_permission` has been deprecated in favor "
"of `django.contrib.auth.get_permission_codename`.", "of `django.contrib.auth.get_permission_codename`.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
return 'delete_%s' % self.model_name return 'delete_%s' % self.model_name
def get_all_related_objects(self, local_only=False, include_hidden=False, def get_all_related_objects(self, local_only=False, include_hidden=False,

View File

@ -5,7 +5,6 @@ The main QuerySet implementation. This provides the public API for the ORM.
import copy import copy
import itertools import itertools
import sys import sys
import warnings
from django.conf import settings from django.conf import settings
from django.core import exceptions from django.core import exceptions
@ -648,10 +647,6 @@ class QuerySet(object):
If select_related(None) is called, the list is cleared. If select_related(None) is called, the list is cleared.
""" """
if 'depth' in kwargs:
warnings.warn('The "depth" keyword argument has been deprecated.\n'
'Use related field names instead.', DeprecationWarning, stacklevel=2)
depth = kwargs.pop('depth', 0)
if kwargs: if kwargs:
raise TypeError('Unexpected keyword arguments to select_related: %s' raise TypeError('Unexpected keyword arguments to select_related: %s'
% (list(kwargs),)) % (list(kwargs),))
@ -659,13 +654,9 @@ class QuerySet(object):
if fields == (None,): if fields == (None,):
obj.query.select_related = False obj.query.select_related = False
elif fields: elif fields:
if depth:
raise TypeError('Cannot pass both "depth" and fields to select_related()')
obj.query.add_select_related(fields) obj.query.add_select_related(fields)
else: else:
obj.query.select_related = True obj.query.select_related = True
if depth:
obj.query.max_depth = depth
return obj return obj
def prefetch_related(self, *lookups): def prefetch_related(self, *lookups):

View File

@ -101,19 +101,19 @@ def set_clean(using=None):
def is_managed(using=None): def is_managed(using=None):
warnings.warn("'is_managed' is deprecated.", warnings.warn("'is_managed' is deprecated.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def managed(flag=True, using=None): def managed(flag=True, using=None):
warnings.warn("'managed' no longer serves a purpose.", warnings.warn("'managed' no longer serves a purpose.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def commit_unless_managed(using=None): def commit_unless_managed(using=None):
warnings.warn("'commit_unless_managed' is now a no-op.", warnings.warn("'commit_unless_managed' is now a no-op.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def rollback_unless_managed(using=None): def rollback_unless_managed(using=None):
warnings.warn("'rollback_unless_managed' is now a no-op.", warnings.warn("'rollback_unless_managed' is now a no-op.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
############### ###############
# Public APIs # # Public APIs #
@ -123,7 +123,7 @@ def get_autocommit(using=None):
""" """
Get the autocommit status of the connection. Get the autocommit status of the connection.
""" """
return get_connection(using).autocommit return get_connection(using).get_autocommit()
def set_autocommit(autocommit, using=None): def set_autocommit(autocommit, using=None):
""" """
@ -175,7 +175,7 @@ def get_rollback(using=None):
""" """
Gets the "needs rollback" flag -- for *advanced use* only. Gets the "needs rollback" flag -- for *advanced use* only.
""" """
return get_connection(using).needs_rollback return get_connection(using).get_rollback()
def set_rollback(rollback, using=None): def set_rollback(rollback, using=None):
""" """
@ -229,15 +229,11 @@ class Atomic(object):
def __enter__(self): def __enter__(self):
connection = get_connection(self.using) connection = get_connection(self.using)
# Ensure we have a connection to the database before testing
# autocommit status.
connection.ensure_connection()
if not connection.in_atomic_block: if not connection.in_atomic_block:
# Reset state when entering an outermost atomic block. # Reset state when entering an outermost atomic block.
connection.commit_on_exit = True connection.commit_on_exit = True
connection.needs_rollback = False connection.needs_rollback = False
if not connection.autocommit: if not connection.get_autocommit():
# Some database adapters (namely sqlite3) don't handle # Some database adapters (namely sqlite3) don't handle
# transactions and savepoints properly when autocommit is off. # transactions and savepoints properly when autocommit is off.
# Turning autocommit back on isn't an option; it would trigger # Turning autocommit back on isn't an option; it would trigger
@ -430,7 +426,7 @@ def autocommit(using=None):
your settings file and want the default behavior in some view functions. your settings file and want the default behavior in some view functions.
""" """
warnings.warn("autocommit is deprecated in favor of set_autocommit.", warnings.warn("autocommit is deprecated in favor of set_autocommit.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def entering(using): def entering(using):
enter_transaction_management(managed=False, using=using) enter_transaction_management(managed=False, using=using)
@ -448,7 +444,7 @@ def commit_on_success(using=None):
control in Web apps. control in Web apps.
""" """
warnings.warn("commit_on_success is deprecated in favor of atomic.", warnings.warn("commit_on_success is deprecated in favor of atomic.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def entering(using): def entering(using):
enter_transaction_management(using=using) enter_transaction_management(using=using)
@ -478,7 +474,7 @@ def commit_manually(using=None):
themselves. themselves.
""" """
warnings.warn("commit_manually is deprecated in favor of set_autocommit.", warnings.warn("commit_manually is deprecated in favor of set_autocommit.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
def entering(using): def entering(using):
enter_transaction_management(using=using) enter_transaction_management(using=using)
@ -500,7 +496,7 @@ def commit_on_success_unless_managed(using=None, savepoint=False):
legacy behavior. legacy behavior.
""" """
connection = get_connection(using) connection = get_connection(using)
if connection.autocommit or connection.in_atomic_block: if connection.get_autocommit() or connection.in_atomic_block:
return atomic(using, savepoint) return atomic(using, savepoint)
else: else:
def entering(using): def entering(using):

View File

@ -85,12 +85,7 @@ class DatabaseErrorWrapper(object):
): ):
db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__) db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
if issubclass(exc_type, db_exc_type): if issubclass(exc_type, db_exc_type):
# Under Python 2.6, exc_value can still be a string. dj_exc_value = dj_exc_type(*exc_value.args)
try:
args = tuple(exc_value.args)
except AttributeError:
args = (exc_value,)
dj_exc_value = dj_exc_type(*args)
dj_exc_value.__cause__ = exc_value dj_exc_value.__cause__ = exc_value
# Only set the 'errors_occurred' flag for errors that may make # Only set the 'errors_occurred' flag for errors that may make
# the connection unusable. # the connection unusable.
@ -174,7 +169,7 @@ class ConnectionHandler(object):
if settings.TRANSACTIONS_MANAGED: if settings.TRANSACTIONS_MANAGED:
warnings.warn( warnings.warn(
"TRANSACTIONS_MANAGED is deprecated. Use AUTOCOMMIT instead.", "TRANSACTIONS_MANAGED is deprecated. Use AUTOCOMMIT instead.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
conn.setdefault('AUTOCOMMIT', False) conn.setdefault('AUTOCOMMIT', False)
conn.setdefault('AUTOCOMMIT', True) conn.setdefault('AUTOCOMMIT', True)
conn.setdefault('ENGINE', 'django.db.backends.dummy') conn.setdefault('ENGINE', 'django.db.backends.dummy')

View File

@ -352,7 +352,7 @@ class BaseForm(object):
if hasattr(field.widget, '_has_changed'): if hasattr(field.widget, '_has_changed'):
warnings.warn("The _has_changed method on widgets is deprecated," warnings.warn("The _has_changed method on widgets is deprecated,"
" define it at field level instead.", " define it at field level instead.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
if field.widget._has_changed(initial_value, data_value): if field.widget._has_changed(initial_value, data_value):
self._changed_data.append(name) self._changed_data.append(name)
elif field._has_changed(initial_value, data_value): elif field._has_changed(initial_value, data_value):

View File

@ -260,7 +260,7 @@ class ModelFormMetaclass(type):
warnings.warn("Creating a ModelForm without either the 'fields' attribute " warnings.warn("Creating a ModelForm without either the 'fields' attribute "
"or the 'exclude' attribute is deprecated - form %s " "or the 'exclude' attribute is deprecated - form %s "
"needs updating" % name, "needs updating" % name,
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
if opts.fields == ALL_FIELDS: if opts.fields == ALL_FIELDS:
# sentinel for fields_for_model to indicate "get the list of # sentinel for fields_for_model to indicate "get the list of
@ -513,7 +513,7 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
getattr(Meta, 'exclude', None) is None): getattr(Meta, 'exclude', None) is None):
warnings.warn("Calling modelform_factory without defining 'fields' or " warnings.warn("Calling modelform_factory without defining 'fields' or "
"'exclude' explicitly is deprecated", "'exclude' explicitly is deprecated",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
# Instatiate type(form) in order to use the same metaclass as form. # Instatiate type(form) in order to use the same metaclass as form.
return type(form)(class_name, (form,), form_class_attrs) return type(form)(class_name, (form,), form_class_attrs)
@ -796,7 +796,7 @@ def modelformset_factory(model, form=ModelForm, formfield_callback=None,
getattr(meta, 'exclude', exclude) is None): getattr(meta, 'exclude', exclude) is None):
warnings.warn("Calling modelformset_factory without defining 'fields' or " warnings.warn("Calling modelformset_factory without defining 'fields' or "
"'exclude' explicitly is deprecated", "'exclude' explicitly is deprecated",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
form = modelform_factory(model, form=form, fields=fields, exclude=exclude, form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
formfield_callback=formfield_callback, formfield_callback=formfield_callback,

View File

@ -636,7 +636,7 @@ class RadioChoiceInput(ChoiceInput):
class RadioInput(RadioChoiceInput): class RadioInput(RadioChoiceInput):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
msg = "RadioInput has been deprecated. Use RadioChoiceInput instead." msg = "RadioInput has been deprecated. Use RadioChoiceInput instead."
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2) warnings.warn(msg, DeprecationWarning, stacklevel=2)
super(RadioInput, self).__init__(*args, **kwargs) super(RadioInput, self).__init__(*args, **kwargs)

View File

@ -2,9 +2,9 @@ from django.http.cookie import SimpleCookie, parse_cookie
from django.http.request import (HttpRequest, QueryDict, UnreadablePostError, from django.http.request import (HttpRequest, QueryDict, UnreadablePostError,
build_request_repr) build_request_repr)
from django.http.response import (HttpResponse, StreamingHttpResponse, from django.http.response import (HttpResponse, StreamingHttpResponse,
CompatibleStreamingHttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, HttpResponsePermanentRedirect,
HttpResponseRedirect, HttpResponseNotModified, HttpResponseBadRequest, HttpResponseNotModified, HttpResponseBadRequest, HttpResponseForbidden,
HttpResponseForbidden, HttpResponseNotFound, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseNotAllowed, HttpResponseGone,
HttpResponseGone, HttpResponseServerError, Http404, BadHeaderError) HttpResponseServerError, Http404, BadHeaderError)
from django.http.utils import (fix_location_header, conditional_content_removal, from django.http.utils import (fix_location_header, conditional_content_removal,
fix_IE_for_attach, fix_IE_for_vary) fix_IE_for_attach, fix_IE_for_vary)

View File

@ -2,7 +2,6 @@ from __future__ import absolute_import, unicode_literals
import datetime import datetime
import time import time
import warnings
from email.header import Header from email.header import Header
try: try:
from urllib.parse import urlparse from urllib.parse import urlparse
@ -98,7 +97,7 @@ class HttpResponseBase(six.Iterator):
status_code = 200 status_code = 200
reason_phrase = None # Use default reason phrase for status code. reason_phrase = None # Use default reason phrase for status code.
def __init__(self, content_type=None, status=None, reason=None, mimetype=None): def __init__(self, content_type=None, status=None, reason=None):
# _headers is a mapping of the lower-case name to the original case of # _headers is a mapping of the lower-case name to the original case of
# the header (required for working with legacy systems) and the header # the header (required for working with legacy systems) and the header
# value. Both the name of the header and its value are ASCII strings. # value. Both the name of the header and its value are ASCII strings.
@ -108,11 +107,6 @@ class HttpResponseBase(six.Iterator):
# This parameter is set by the handler. It's necessary to preserve the # This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished. # historical behavior of request_finished.
self._handler_class = None self._handler_class = None
if mimetype:
warnings.warn("Using mimetype keyword argument is deprecated, use"
" content_type instead",
DeprecationWarning, stacklevel=2)
content_type = mimetype
if not content_type: if not content_type:
content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE, content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
self._charset) self._charset)
@ -337,53 +331,27 @@ class HttpResponse(HttpResponseBase):
else: else:
__str__ = serialize __str__ = serialize
def _consume_content(self):
# If the response was instantiated with an iterator, when its content
# is accessed, the iterator is going be exhausted and the content
# loaded in memory. At this point, it's better to abandon the original
# iterator and save the content for later reuse. This is a temporary
# solution. See the comment in __iter__ below for the long term plan.
if self._base_content_is_iter:
self.content = b''.join(self.make_bytes(e) for e in self._container)
@property @property
def content(self): def content(self):
self._consume_content()
return b''.join(self.make_bytes(e) for e in self._container) return b''.join(self.make_bytes(e) for e in self._container)
@content.setter @content.setter
def content(self, value): def content(self, value):
if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)): if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)):
self._container = value
self._base_content_is_iter = True
if hasattr(value, 'close'): if hasattr(value, 'close'):
self._closable_objects.append(value) self._closable_objects.append(value)
else: value = b''.join(self.make_bytes(e) for e in value)
self._container = [value] self._container = [value]
self._base_content_is_iter = False
def __iter__(self): def __iter__(self):
# Raise a deprecation warning only if the content wasn't consumed yet,
# because the response may be intended to be streamed.
# Once the deprecation completes, iterators should be consumed upon
# assignment rather than upon access. The _consume_content method
# should be removed. See #6527.
if self._base_content_is_iter:
warnings.warn(
'Creating streaming responses with `HttpResponse` is '
'deprecated. Use `StreamingHttpResponse` instead '
'if you need the streaming behavior.',
DeprecationWarning, stacklevel=2)
if not hasattr(self, '_iterator'): if not hasattr(self, '_iterator'):
self._iterator = iter(self._container) self._iterator = iter(self._container)
return self return self
def write(self, content): def write(self, content):
self._consume_content()
self._container.append(content) self._container.append(content)
def tell(self): def tell(self):
self._consume_content()
return len(self.content) return len(self.content)
@ -421,35 +389,6 @@ class StreamingHttpResponse(HttpResponseBase):
self._closable_objects.append(value) self._closable_objects.append(value)
class CompatibleStreamingHttpResponse(StreamingHttpResponse):
"""
This class maintains compatibility with middleware that doesn't know how
to handle the content of a streaming response by exposing a `content`
attribute that will consume and cache the content iterator when accessed.
These responses will stream only if no middleware attempts to access the
`content` attribute. Otherwise, they will behave like a regular response,
and raise a `DeprecationWarning`.
"""
@property
def content(self):
warnings.warn(
'Accessing the `content` attribute on a streaming response is '
'deprecated. Use the `streaming_content` attribute instead.',
DeprecationWarning, stacklevel=2)
content = b''.join(self)
self.streaming_content = [content]
return content
@content.setter
def content(self, content):
warnings.warn(
'Accessing the `content` attribute on a streaming response is '
'deprecated. Use the `streaming_content` attribute instead.',
DeprecationWarning, stacklevel=2)
self.streaming_content = [content]
class HttpResponseRedirectBase(HttpResponse): class HttpResponseRedirectBase(HttpResponse):
allowed_schemes = ['http', 'https', 'ftp'] allowed_schemes = ['http', 'https', 'ftp']
@ -483,7 +422,6 @@ class HttpResponseNotModified(HttpResponse):
if value: if value:
raise AttributeError("You cannot set content to a 304 (Not Modified) response") raise AttributeError("You cannot set content to a 304 (Not Modified) response")
self._container = [] self._container = []
self._base_content_is_iter = False
class HttpResponseBadRequest(HttpResponse): class HttpResponseBadRequest(HttpResponse):

View File

@ -199,7 +199,7 @@ class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
if self.cache_anonymous_only: if self.cache_anonymous_only:
msg = "CACHE_MIDDLEWARE_ANONYMOUS_ONLY has been deprecated and will be removed in Django 1.8." msg = "CACHE_MIDDLEWARE_ANONYMOUS_ONLY has been deprecated and will be removed in Django 1.8."
warnings.warn(msg, PendingDeprecationWarning, stacklevel=1) warnings.warn(msg, DeprecationWarning, stacklevel=1)
self.cache = get_cache(self.cache_alias, **cache_kwargs) self.cache = get_cache(self.cache_alias, **cache_kwargs)
self.cache_timeout = self.cache.default_timeout self.cache_timeout = self.cache.default_timeout

View File

@ -110,7 +110,7 @@ class CommonMiddleware(object):
if settings.SEND_BROKEN_LINK_EMAILS: if settings.SEND_BROKEN_LINK_EMAILS:
warnings.warn("SEND_BROKEN_LINK_EMAILS is deprecated. " warnings.warn("SEND_BROKEN_LINK_EMAILS is deprecated. "
"Use BrokenLinkEmailsMiddleware instead.", "Use BrokenLinkEmailsMiddleware instead.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
BrokenLinkEmailsMiddleware().process_response(request, response) BrokenLinkEmailsMiddleware().process_response(request, response)
if settings.USE_ETAGS: if settings.USE_ETAGS:

View File

@ -1,6 +1,6 @@
"""XViewMiddleware has been moved to django.contrib.admindocs.middleware.""" """XViewMiddleware has been moved to django.contrib.admindocs.middleware."""
import warnings import warnings
warnings.warn(__doc__, PendingDeprecationWarning, stacklevel=2) warnings.warn(__doc__, DeprecationWarning, stacklevel=2)
from django.contrib.admindocs.middleware import XViewMiddleware from django.contrib.admindocs.middleware import XViewMiddleware

View File

@ -14,7 +14,7 @@ class TransactionMiddleware(object):
def __init__(self): def __init__(self):
warnings.warn( warnings.warn(
"TransactionMiddleware is deprecated in favor of ATOMIC_REQUESTS.", "TransactionMiddleware is deprecated in favor of ATOMIC_REQUESTS.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
if connection.settings_dict['ATOMIC_REQUESTS']: if connection.settings_dict['ATOMIC_REQUESTS']:
raise MiddlewareNotUsed raise MiddlewareNotUsed

View File

@ -3,8 +3,6 @@ This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake. for convenience's sake.
""" """
import warnings
from django.template import loader, RequestContext from django.template import loader, RequestContext
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
@ -20,12 +18,6 @@ def render_to_response(*args, **kwargs):
""" """
httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)}
mimetype = kwargs.pop('mimetype', None)
if mimetype:
warnings.warn("The mimetype keyword argument is deprecated, use "
"content_type instead", DeprecationWarning, stacklevel=2)
httpresponse_kwargs['content_type'] = mimetype
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
def render(request, *args, **kwargs): def render(request, *args, **kwargs):

View File

@ -568,7 +568,7 @@ def cycle(parser, token, escape=False):
"'The `cycle` template tag is changing to escape its arguments; " "'The `cycle` template tag is changing to escape its arguments; "
"the non-autoescaping version is deprecated. Load it " "the non-autoescaping version is deprecated. Load it "
"from the `future` tag library to start using the new behavior.", "from the `future` tag library to start using the new behavior.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
# Note: This returns the exact same node on each {% cycle name %} call; # Note: This returns the exact same node on each {% cycle name %} call;
# that is, the node object returned from {% cycle a b c as name %} and the # that is, the node object returned from {% cycle a b c as name %} and the
@ -712,7 +712,7 @@ def firstof(parser, token, escape=False):
"'The `firstof` template tag is changing to escape its arguments; " "'The `firstof` template tag is changing to escape its arguments; "
"the non-autoescaping version is deprecated. Load it " "the non-autoescaping version is deprecated. Load it "
"from the `future` tag library to start using the new behavior.", "from the `future` tag library to start using the new behavior.",
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
bits = token.split_contents()[1:] bits = token.split_contents()[1:]
if len(bits) < 1: if len(bits) < 1:

View File

@ -10,8 +10,7 @@ class ContentNotRenderedError(Exception):
class SimpleTemplateResponse(HttpResponse): class SimpleTemplateResponse(HttpResponse):
rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks'] rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks']
def __init__(self, template, context=None, content_type=None, status=None, def __init__(self, template, context=None, content_type=None, status=None):
mimetype=None):
# It would seem obvious to call these next two members 'template' and # It would seem obvious to call these next two members 'template' and
# 'context', but those names are reserved as part of the test Client # 'context', but those names are reserved as part of the test Client
# API. To avoid the name collision, we use tricky-to-debug problems # API. To avoid the name collision, we use tricky-to-debug problems
@ -23,8 +22,7 @@ class SimpleTemplateResponse(HttpResponse):
# content argument doesn't make sense here because it will be replaced # content argument doesn't make sense here because it will be replaced
# with rendered template so we always pass empty string in order to # with rendered template so we always pass empty string in order to
# prevent errors and provide shorter signature. # prevent errors and provide shorter signature.
super(SimpleTemplateResponse, self).__init__('', content_type, status, super(SimpleTemplateResponse, self).__init__('', content_type, status)
mimetype)
# _is_rendered tracks whether the template and context has been baked # _is_rendered tracks whether the template and context has been baked
# into a final response. # into a final response.
@ -139,7 +137,7 @@ class TemplateResponse(SimpleTemplateResponse):
['_request', '_current_app'] ['_request', '_current_app']
def __init__(self, request, template, context=None, content_type=None, def __init__(self, request, template, context=None, content_type=None,
status=None, mimetype=None, current_app=None): status=None, current_app=None):
# self.request gets over-written by django.test.client.Client - and # self.request gets over-written by django.test.client.Client - and
# unlike context_data and template_name the _request should not # unlike context_data and template_name the _request should not
# be considered part of the public API. # be considered part of the public API.
@ -148,7 +146,7 @@ class TemplateResponse(SimpleTemplateResponse):
# having to avoid needing to create the RequestContext directly # having to avoid needing to create the RequestContext directly
self._current_app = current_app self._current_app = current_app
super(TemplateResponse, self).__init__( super(TemplateResponse, self).__init__(
template, context, content_type, status, mimetype) template, context, content_type, status)
def resolve_context(self, context): def resolve_context(self, context):
"""Convert context data into a full RequestContext object """Convert context data into a full RequestContext object

View File

@ -54,7 +54,7 @@ import warnings
warnings.warn( warnings.warn(
"The django.test._doctest module is deprecated; " "The django.test._doctest module is deprecated; "
"use the doctest module from the Python standard library instead.", "use the doctest module from the Python standard library instead.",
PendingDeprecationWarning) DeprecationWarning)
__docformat__ = 'reStructuredText en' __docformat__ = 'reStructuredText en'

View File

@ -1,12 +1,12 @@
import os import os
from optparse import make_option from optparse import make_option
import unittest
from unittest import TestSuite, defaultTestLoader
from django.conf import settings from django.conf import settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase from django.test import TestCase
from django.test.utils import setup_test_environment, teardown_test_environment from django.test.utils import setup_test_environment, teardown_test_environment
from django.utils import unittest
from django.utils.unittest import TestSuite, defaultTestLoader
class DiscoverRunner(object): class DiscoverRunner(object):

View File

@ -12,6 +12,8 @@ from django.db.models import get_app, get_apps
from django.test import _doctest as doctest from django.test import _doctest as doctest
from django.test import runner from django.test import runner
from django.test.utils import compare_xml, strip_quotes from django.test.utils import compare_xml, strip_quotes
# django.utils.unittest is deprecated, but so is django.test.simple,
# and the latter will be removed before the former.
from django.utils import unittest from django.utils import unittest
from django.utils.importlib import import_module from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule from django.utils.module_loading import module_has_submodule
@ -21,7 +23,7 @@ __all__ = ('DjangoTestSuiteRunner',)
warnings.warn( warnings.warn(
"The django.test.simple module and DjangoTestSuiteRunner are deprecated; " "The django.test.simple module and DjangoTestSuiteRunner are deprecated; "
"use django.test.runner.DiscoverRunner instead.", "use django.test.runner.DiscoverRunner instead.",
PendingDeprecationWarning) DeprecationWarning)
# The module name for tests outside models.py # The module name for tests outside models.py
TEST_MODULE = 'tests' TEST_MODULE = 'tests'

View File

@ -8,14 +8,16 @@ import json
import os import os
import re import re
import sys import sys
import select
import socket
import threading
import unittest
from unittest import skipIf # Imported here for backward compatibility
from unittest.util import safe_repr
try: try:
from urllib.parse import urlsplit, urlunsplit from urllib.parse import urlsplit, urlunsplit
except ImportError: # Python 2 except ImportError: # Python 2
from urlparse import urlsplit, urlunsplit from urlparse import urlsplit, urlunsplit
import select
import socket
import threading
import warnings
from django.conf import settings from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler from django.contrib.staticfiles.handlers import StaticFilesHandler
@ -37,10 +39,8 @@ from django.test.html import HTMLParseError, parse_html
from django.test.signals import template_rendered from django.test.signals import template_rendered
from django.test.utils import (CaptureQueriesContext, ContextList, from django.test.utils import (CaptureQueriesContext, ContextList,
override_settings, compare_xml) override_settings, compare_xml)
from django.utils import six, unittest as ut2 from django.utils import six
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.unittest import skipIf # Imported here for backward compatibility
from django.utils.unittest.util import safe_repr
from django.views.static import serve from django.views.static import serve
@ -156,16 +156,12 @@ class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext):
return '%s was rendered.' % self.template_name return '%s was rendered.' % self.template_name
class SimpleTestCase(ut2.TestCase): class SimpleTestCase(unittest.TestCase):
# The class we'll use for the test client self.client. # The class we'll use for the test client self.client.
# Can be overridden in derived classes. # Can be overridden in derived classes.
client_class = Client client_class = Client
_warn_txt = ("save_warnings_state/restore_warnings_state "
"django.test.*TestCase methods are deprecated. Use Python's "
"warnings.catch_warnings context manager instead.")
def __call__(self, result=None): def __call__(self, result=None):
""" """
Wrapper around default __call__ method to perform common Django test Wrapper around default __call__ method to perform common Django test
@ -225,21 +221,6 @@ class SimpleTestCase(ut2.TestCase):
settings.ROOT_URLCONF = self._old_root_urlconf settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches() clear_url_caches()
def save_warnings_state(self):
"""
Saves the state of the warnings module
"""
warnings.warn(self._warn_txt, DeprecationWarning, stacklevel=2)
self._warnings_state = warnings.filters[:]
def restore_warnings_state(self):
"""
Restores the state of the warnings module to the state
saved by save_warnings_state()
"""
warnings.warn(self._warn_txt, DeprecationWarning, stacklevel=2)
warnings.filters = self._warnings_state[:]
def settings(self, **kwargs): def settings(self, **kwargs):
""" """
A context manager that temporarily sets a setting and reverts A context manager that temporarily sets a setting and reverts
@ -906,7 +887,7 @@ def _deferredSkip(condition, reason):
@wraps(test_func) @wraps(test_func)
def skip_wrapper(*args, **kwargs): def skip_wrapper(*args, **kwargs):
if condition(): if condition():
raise ut2.SkipTest(reason) raise unittest.SkipTest(reason)
return test_func(*args, **kwargs) return test_func(*args, **kwargs)
test_item = skip_wrapper test_item = skip_wrapper
else: else:

View File

@ -124,31 +124,6 @@ def teardown_test_environment():
del mail.outbox del mail.outbox
warn_txt = ("get_warnings_state/restore_warnings_state functions from "
"django.test.utils are deprecated. Use Python's warnings.catch_warnings() "
"context manager instead.")
def get_warnings_state():
"""
Returns an object containing the state of the warnings module
"""
# There is no public interface for doing this, but this implementation of
# get_warnings_state and restore_warnings_state appears to work on Python
# 2.4 to 2.7.
warnings.warn(warn_txt, DeprecationWarning, stacklevel=2)
return warnings.filters[:]
def restore_warnings_state(state):
"""
Restores the state of the warnings module when passed an object that was
returned by get_warnings_state()
"""
warnings.warn(warn_txt, DeprecationWarning, stacklevel=2)
warnings.filters = state[:]
def get_runner(settings, test_runner_class=None): def get_runner(settings, test_runner_class=None):
if not test_runner_class: if not test_runner_class:
test_runner_class = settings.TEST_RUNNER test_runner_class = settings.TEST_RUNNER
@ -402,13 +377,14 @@ class CaptureQueriesContext(object):
class IgnoreDeprecationWarningsMixin(object): class IgnoreDeprecationWarningsMixin(object):
warning_class = DeprecationWarning warning_classes = [DeprecationWarning]
def setUp(self): def setUp(self):
super(IgnoreDeprecationWarningsMixin, self).setUp() super(IgnoreDeprecationWarningsMixin, self).setUp()
self.catch_warnings = warnings.catch_warnings() self.catch_warnings = warnings.catch_warnings()
self.catch_warnings.__enter__() self.catch_warnings.__enter__()
warnings.filterwarnings("ignore", category=self.warning_class) for warning_class in self.warning_classes:
warnings.filterwarnings("ignore", category=warning_class)
def tearDown(self): def tearDown(self):
self.catch_warnings.__exit__(*sys.exc_info()) self.catch_warnings.__exit__(*sys.exc_info())
@ -417,7 +393,12 @@ class IgnoreDeprecationWarningsMixin(object):
class IgnorePendingDeprecationWarningsMixin(IgnoreDeprecationWarningsMixin): class IgnorePendingDeprecationWarningsMixin(IgnoreDeprecationWarningsMixin):
warning_class = PendingDeprecationWarning warning_classes = [PendingDeprecationWarning]
class IgnoreAllDeprecationWarningsMixin(IgnoreDeprecationWarningsMixin):
warning_classes = [PendingDeprecationWarning, DeprecationWarning]
@contextmanager @contextmanager

View File

@ -1,5 +1,4 @@
import copy import copy
import warnings
from django.utils import six from django.utils import six
@ -217,31 +216,6 @@ class SortedDict(dict):
self.keyOrder.append(key) self.keyOrder.append(key)
return super(SortedDict, self).setdefault(key, default) return super(SortedDict, self).setdefault(key, default)
def value_for_index(self, index):
"""Returns the value of the item at the given zero-based index."""
# This, and insert() are deprecated because they cannot be implemented
# using collections.OrderedDict (Python 2.7 and up), which we'll
# eventually switch to
warnings.warn(
"SortedDict.value_for_index is deprecated", DeprecationWarning,
stacklevel=2
)
return self[self.keyOrder[index]]
def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
warnings.warn(
"SortedDict.insert is deprecated", DeprecationWarning,
stacklevel=2
)
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value)
def copy(self): def copy(self):
"""Returns a copy of this object.""" """Returns a copy of this object."""
# This way of initializing the copy means it works for subclasses, too. # This way of initializing the copy means it works for subclasses, too.

View File

@ -1,3 +1,8 @@
import warnings
warnings.warn("django.utils.dictconfig will be removed in Django 1.9.",
PendingDeprecationWarning, stacklevel=2)
# This is a copy of the Python logging.config.dictconfig module, # This is a copy of the Python logging.config.dictconfig module,
# reproduced with permission. It is provided here for backwards # reproduced with permission. It is provided here for backwards
# compatibility for Python versions prior to 2.7. # compatibility for Python versions prior to 2.7.

View File

@ -8,7 +8,6 @@ try:
from urllib.parse import quote from urllib.parse import quote
except ImportError: # Python 2 except ImportError: # Python 2
from urllib import quote from urllib import quote
import warnings
from django.utils.functional import Promise from django.utils.functional import Promise
from django.utils import six from django.utils import six
@ -23,29 +22,6 @@ class DjangoUnicodeDecodeError(UnicodeDecodeError):
return '%s. You passed in %r (%s)' % (original, self.obj, return '%s. You passed in %r (%s)' % (original, self.obj,
type(self.obj)) type(self.obj))
class StrAndUnicode(object):
"""
A class that derives __str__ from __unicode__.
On Python 2, __str__ returns the output of __unicode__ encoded as a UTF-8
bytestring. On Python 3, __str__ returns the output of __unicode__.
Useful as a mix-in. If you support Python 2 and 3 with a single code base,
you can inherit this mix-in and just define __unicode__.
"""
def __init__(self, *args, **kwargs):
warnings.warn("StrAndUnicode is deprecated. Define a __str__ method "
"and apply the @python_2_unicode_compatible decorator "
"instead.", DeprecationWarning, stacklevel=2)
super(StrAndUnicode, self).__init__(*args, **kwargs)
if six.PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode('utf-8')
def python_2_unicode_compatible(klass): def python_2_unicode_compatible(klass):
""" """
A decorator that defines __unicode__ and __str__ methods under Python 2. A decorator that defines __unicode__ and __str__ methods under Python 2.

View File

@ -139,7 +139,7 @@ def _detect_image_library():
warnings.warn( warnings.warn(
"Support for the PIL will be removed in Django 1.8. Please " + "Support for the PIL will be removed in Django 1.8. Please " +
"uninstall it & install Pillow instead.", "uninstall it & install Pillow instead.",
PendingDeprecationWarning DeprecationWarning
) )
return PILImage, PIL_imaging, PILImageFile return PILImage, PIL_imaging, PILImageFile

View File

@ -5,9 +5,7 @@ these implementations if necessary.
""" """
import collections import collections
import itertools
import sys import sys
import warnings
def is_iterable(x): def is_iterable(x):
@ -29,8 +27,3 @@ def is_iterator(x):
if sys.version_info >= (2, 7): if sys.version_info >= (2, 7):
return isinstance(x, collections.Iterator) return isinstance(x, collections.Iterator)
return isinstance(x, collections.Iterator) and hasattr(x, '__iter__') return isinstance(x, collections.Iterator) and hasattr(x, '__iter__')
def product(*args, **kwds):
warnings.warn("django.utils.itercompat.product is deprecated; use the native version instead",
DeprecationWarning, stacklevel=2)
return itertools.product(*args, **kwds)

View File

@ -6,22 +6,9 @@ from django.core import mail
from django.core.mail import get_connection from django.core.mail import get_connection
from django.views.debug import ExceptionReporter, get_exception_reporter_filter from django.views.debug import ExceptionReporter, get_exception_reporter_filter
# Imports kept for backwards-compatibility in Django 1.7.
# Make sure a NullHandler is available from logging import NullHandler
# This was added in Python 2.7/3.2 from logging.config import dictConfig
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Make sure that dictConfig is available
# This was added in Python 2.7/3.2
try:
from logging.config import dictConfig
except ImportError:
from django.utils.dictconfig import dictConfig
getLogger = logging.getLogger getLogger = logging.getLogger
@ -46,7 +33,7 @@ DEFAULT_LOGGING = {
'class': 'logging.StreamHandler', 'class': 'logging.StreamHandler',
}, },
'null': { 'null': {
'class': 'django.utils.log.NullHandler', 'class': 'logging.NullHandler',
}, },
'mail_admins': { 'mail_admins': {
'level': 'ERROR', 'level': 'ERROR',

View File

@ -1,31 +0,0 @@
# Django 1.5 only supports Python >= 2.6, where the standard library includes
# the json module. Previous version of Django shipped a copy for Python < 2.6.
# For backwards compatibility, we're keeping an importable json module
# at this location, with the same lookup sequence.
# Avoid shadowing the simplejson module
from __future__ import absolute_import
import warnings
warnings.warn("django.utils.simplejson is deprecated; use json instead.",
DeprecationWarning, stacklevel=2)
try:
import simplejson
except ImportError:
use_simplejson = False
else:
# The system-installed version has priority providing it is either not an
# earlier version or it contains the C speedups.
from json import __version__ as stdlib_json_version
use_simplejson = (hasattr(simplejson, '_speedups') or
simplejson.__version__.split('.') >= stdlib_json_version.split('.'))
# Make sure we copy over the version. See #17071
if use_simplejson:
from simplejson import *
from simplejson import __version__
else:
from json import *
from json import __version__

11
django/utils/unittest.py Normal file
View File

@ -0,0 +1,11 @@
from __future__ import absolute_import
import warnings
warnings.warn("django.utils.unittest will be removed in Django 1.9.",
PendingDeprecationWarning, stacklevel=2)
try:
from unittest2 import *
except ImportError:
from unittest import *

View File

@ -1,80 +0,0 @@
"""
unittest2
unittest2 is a backport of the new features added to the unittest testing
framework in Python 2.7. It is tested to run on Python 2.4 - 2.6.
To use unittest2 instead of unittest simply replace ``import unittest`` with
``import unittest2``.
Copyright (c) 1999-2003 Steve Purcell
Copyright (c) 2003-2010 Python Software Foundation
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
import sys
# Django hackery to load the appropriate version of unittest
try:
# check the system path first
from unittest2 import *
except ImportError:
if sys.version_info >= (2,7):
# unittest2 features are native in Python 2.7
from unittest import *
else:
# otherwise use our bundled version
__all__ = ['TestResult', 'TestCase', 'TestSuite',
'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
'expectedFailure', 'TextTestResult', '__version__', 'collector']
__version__ = '0.5.1'
# Expose obsolete functions for backwards compatibility
__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
from django.utils.unittest.collector import collector
from django.utils.unittest.result import TestResult
from django.utils.unittest.case import \
TestCase, FunctionTestCase, SkipTest, skip, skipIf,\
skipUnless, expectedFailure
from django.utils.unittest.suite import BaseTestSuite, TestSuite
from django.utils.unittest.loader import \
TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,\
findTestCases
from django.utils.unittest.main import TestProgram, main, main_
from django.utils.unittest.runner import TextTestRunner, TextTestResult
try:
from django.utils.unittest.signals import\
installHandler, registerResult, removeResult, removeHandler
except ImportError:
# Compatibility with platforms that don't have the signal module
pass
else:
__all__.extend(['installHandler', 'registerResult', 'removeResult',
'removeHandler'])
# deprecated
_TextTestResult = TextTestResult
__unittest = True

View File

@ -1,10 +0,0 @@
"""Main entry point"""
import sys
if sys.argv[0].endswith("__main__.py"):
sys.argv[0] = "unittest2"
__unittest = True
from django.utils.unittest.main import main_
main_()

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +0,0 @@
import os
import sys
from django.utils.unittest.loader import defaultTestLoader
def collector():
# import __main__ triggers code re-execution
__main__ = sys.modules['__main__']
setupDir = os.path.abspath(os.path.dirname(__main__.__file__))
return defaultTestLoader.discover(setupDir)

View File

@ -1,64 +0,0 @@
import os
import sys
try:
from functools import wraps
except ImportError:
# only needed for Python 2.4
def wraps(_):
def _wraps(func):
return func
return _wraps
__unittest = True
def _relpath_nt(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.path.sep)
path_list = os.path.abspath(path).split(os.path.sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = os.path.splitunc(path)
unc_start, rest = os.path.splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.path.curdir
return os.path.join(*rel_list)
# default to posixpath definition
def _relpath_posix(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.path.sep)
path_list = os.path.abspath(path).split(os.path.sep)
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonprefix([start_list, path_list]))
rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.path.curdir
return os.path.join(*rel_list)
if os.path is sys.modules.get('ntpath'):
relpath = _relpath_nt
else:
relpath = _relpath_posix

Some files were not shown because too many files have changed in this diff Show More