Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compat cleanup #5581

Merged
merged 5 commits into from
Nov 10, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions rest_framework/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,29 @@
versions of Django/Python, and compatibility wrappers around optional packages.
"""

# flake8: noqa
from __future__ import unicode_literals

import inspect

import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import \
MaxLengthValidator as DjangoMaxLengthValidator
from django.core.validators import MaxValueValidator as DjangoMaxValueValidator
from django.core.validators import \
MinLengthValidator as DjangoMinLengthValidator
from django.core.validators import MinValueValidator as DjangoMinValueValidator
from django.core import validators
from django.core.exceptions import ImproperlyConfigured
from django.db import connection, models, transaction
from django.template import Context, RequestContext, Template
from django.utils import six
from django.views.generic import View

try:
from django.urls import (
NoReverseMatch, URLPattern as RegexURLPattern, URLResolver as RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
from django.urls import ( # noqa
URLPattern,
URLResolver,
)

except ImportError:
from django.core.urlresolvers import ( # Will be removed in Django 2.0
NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
# Will be removed in Django 2.0
from django.urls import ( # noqa
RegexURLPattern as URLPattern,
RegexURLResolver as URLResolver,
)


Expand All @@ -47,11 +42,11 @@ def make_url_resolver(regex, urlpatterns):
try:
# Django 2.0
from django.urls.resolvers import RegexPattern
return RegexURLResolver(RegexPattern(regex), urlpatterns)
return URLResolver(RegexPattern(regex), urlpatterns)

except ImportError:
# Django < 2.0
return RegexURLResolver(regex, urlpatterns)
return URLResolver(regex, urlpatterns)


def unicode_repr(instance):
Expand Down Expand Up @@ -152,7 +147,7 @@ def _resolve_model(obj):
guardian = None
try:
if 'guardian' in settings.INSTALLED_APPS:
import guardian
import guardian # noqa
except ImportError:
pass

Expand Down Expand Up @@ -229,7 +224,7 @@ def pygments_css(style):

class CodeBlockPreprocessor(Preprocessor):
pattern = re.compile(
r'^\s*``` *([^\n]+)\n(.+?)^\s*```', re.M|re.S)
r'^\s*``` *([^\n]+)\n(.+?)^\s*```', re.M | re.S)

formatter = HtmlFormatter()

Expand All @@ -239,9 +234,9 @@ def repl(m):
lexer = get_lexer_by_name(m.group(1))
except (ValueError, NameError):
lexer = TextLexer()
code = m.group(2).replace('\t',' ')
code = m.group(2).replace('\t', ' ')
code = pygments.highlight(code, lexer, self.formatter)
code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />').replace('\\@','@')
code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />').replace('\\@', '@')
return '\n\n%s\n\n' % code
ret = self.pattern.sub(repl, "\n".join(lines))
return ret.split("\n")
Expand All @@ -254,7 +249,7 @@ def md_filter_add_syntax_highlight(md):
return False

try:
import pytz
import pytz # noqa
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Starting with Django 1.11, pytz is a Django requirement. So django-rest-framework can expect it to exist. I think adding a comment with this information would be helpful so that when Django 1.10 is dropped it is noticed and this workaround is removed.

from pytz.exceptions import InvalidTimeError
except ImportError:
InvalidTimeError = Exception
Expand All @@ -279,22 +274,28 @@ class CustomValidatorMessage(object):

Ref: https://github.com/encode/django-rest-framework/pull/5452
"""

def __init__(self, *args, **kwargs):
self.message = kwargs.pop('message', self.message)
super(CustomValidatorMessage, self).__init__(*args, **kwargs)

class MinValueValidator(CustomValidatorMessage, DjangoMinValueValidator):

class MinValueValidator(CustomValidatorMessage, validators.MinValueValidator):
pass

class MaxValueValidator(CustomValidatorMessage, DjangoMaxValueValidator):

class MaxValueValidator(CustomValidatorMessage, validators.MaxValueValidator):
pass

class MinLengthValidator(CustomValidatorMessage, DjangoMinLengthValidator):

class MinLengthValidator(CustomValidatorMessage, validators.MinLengthValidator):
pass

class MaxLengthValidator(CustomValidatorMessage, DjangoMaxLengthValidator):

class MaxLengthValidator(CustomValidatorMessage, validators.MaxLengthValidator):
pass


def set_rollback():
if hasattr(transaction, 'set_rollback'):
if connection.settings_dict.get('ATOMIC_REQUESTS', False):
Expand All @@ -318,4 +319,3 @@ def authenticate(request=None, **credentials):
return authenticate(**credentials)
else:
return authenticate(request=request, **credentials)

4 changes: 1 addition & 3 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.urls import NoReverseMatch, Resolver404, get_script_prefix, resolve
from django.utils import six
from django.utils.encoding import (
python_2_unicode_compatible, smart_text, uri_to_iri
)
from django.utils.six.moves.urllib import parse as urlparse
from django.utils.translation import ugettext_lazy as _

from rest_framework.compat import (
NoReverseMatch, Resolver404, get_script_prefix, resolve
)
from rest_framework.fields import (
Field, empty, get_attribute, is_simple_callable, iter_options
)
Expand Down
4 changes: 2 additions & 2 deletions rest_framework/reverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"""
from __future__ import unicode_literals

from django.urls import reverse as django_reverse
from django.urls import NoReverseMatch
from django.utils import six
from django.utils.functional import lazy

from rest_framework.compat import reverse as django_reverse
from rest_framework.compat import NoReverseMatch
from rest_framework.settings import api_settings
from rest_framework.utils.urls import replace_query_param

Expand Down
2 changes: 1 addition & 1 deletion rest_framework/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@

from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.urls import NoReverseMatch

from rest_framework import views
from rest_framework.compat import NoReverseMatch
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.schemas import SchemaGenerator
Expand Down
6 changes: 3 additions & 3 deletions rest_framework/schemas/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from rest_framework import exceptions
from rest_framework.compat import (
RegexURLPattern, RegexURLResolver, coreapi, coreschema, get_regex_pattern
URLPattern, URLResolver, coreapi, coreschema, get_regex_pattern
)
from rest_framework.request import clone_request
from rest_framework.settings import api_settings
Expand Down Expand Up @@ -165,15 +165,15 @@ def get_api_endpoints(self, patterns=None, prefix=''):

for pattern in patterns:
path_regex = prefix + get_regex_pattern(pattern)
if isinstance(pattern, RegexURLPattern):
if isinstance(pattern, URLPattern):
path = self.get_path_from_regex(path_regex)
callback = pattern.callback
if self.should_include_endpoint(path, callback):
for method in self.get_allowed_methods(callback):
endpoint = (path, method, callback)
api_endpoints.append(endpoint)

elif isinstance(pattern, RegexURLResolver):
elif isinstance(pattern, URLResolver):
nested_endpoints = self.get_api_endpoints(
patterns=pattern.url_patterns,
prefix=path_regex
Expand Down
6 changes: 2 additions & 4 deletions rest_framework/templatetags/rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@

from django import template
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils import six
from django.utils.encoding import force_text, iri_to_uri
from django.utils.html import escape, format_html, smart_urlquote
from django.utils.safestring import SafeData, mark_safe

from rest_framework.compat import (
NoReverseMatch, apply_markdown, pygments_highlight, reverse
)
from rest_framework.compat import apply_markdown, pygments_highlight
from rest_framework.renderers import HTMLFormRenderer
from rest_framework.utils.urls import replace_query_param

Expand Down
4 changes: 2 additions & 2 deletions rest_framework/urlpatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

from django.conf.urls import include, url

from rest_framework.compat import RegexURLResolver, get_regex_pattern
from rest_framework.compat import URLResolver, get_regex_pattern
from rest_framework.settings import api_settings


def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLResolver):
if isinstance(urlpattern, URLResolver):
# Set of included URL patterns
regex = get_regex_pattern(urlpattern)
namespace = urlpattern.namespace
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/utils/breadcrumbs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import unicode_literals

from rest_framework.compat import get_script_prefix, resolve
from django.urls import get_script_prefix, resolve


def get_breadcrumbs(url, request=None):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
from django.contrib.auth.models import Group, Permission, User
from django.db import models
from django.test import TestCase
from django.urls import ResolverMatch

from rest_framework import (
HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers,
status, views
)
from rest_framework.compat import ResolverMatch, guardian
from rest_framework.compat import guardian
from rest_framework.filters import DjangoObjectPermissionsFilter
from rest_framework.routers import DefaultRouter
from rest_framework.test import APIRequestFactory
Expand Down
2 changes: 1 addition & 1 deletion tests/test_reverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from django.conf.urls import url
from django.test import TestCase, override_settings
from django.urls import NoReverseMatch

from rest_framework.compat import NoReverseMatch
from rest_framework.reverse import reverse
from rest_framework.test import APIRequestFactory

Expand Down
3 changes: 2 additions & 1 deletion tests/test_urlpatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

from django.conf.urls import include, url
from django.test import TestCase
from django.urls import Resolver404

from rest_framework.compat import Resolver404, make_url_resolver
from rest_framework.compat import make_url_resolver
from rest_framework.test import APIRequestFactory
from rest_framework.urlpatterns import format_suffix_patterns

Expand Down
3 changes: 1 addition & 2 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.core.exceptions import ObjectDoesNotExist

from rest_framework.compat import NoReverseMatch
from django.urls import NoReverseMatch


class MockObject(object):
Expand Down