Imported django.http classes instead of django.http.

This commit is contained in:
Asif Saifuddin Auvi 2017-02-25 12:48:20 +06:00 committed by Tim Graham
parent 6b00af5014
commit 5f3a689f71
13 changed files with 69 additions and 58 deletions

View File

@ -1,5 +1,5 @@
from django import http
from django.conf import settings from django.conf import settings
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
@ -23,6 +23,6 @@ class XViewMiddleware(MiddlewareMixin):
) )
if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
(request.user.is_active and request.user.is_staff)): (request.user.is_active and request.user.is_staff)):
response = http.HttpResponse() response = HttpResponse()
response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__) response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__)
return response return response

View File

@ -1,8 +1,8 @@
from django import http
from django.apps import apps from django.apps import apps
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.requests import RequestSite from django.contrib.sites.requests import RequestSite
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseRedirect
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
@ -14,18 +14,24 @@ def shortcut(request, content_type_id, object_id):
try: try:
content_type = ContentType.objects.get(pk=content_type_id) content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class(): if not content_type.model_class():
raise http.Http404(_("Content type %(ct_id)s object has no associated model") % raise Http404(
{'ct_id': content_type_id}) _("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id}
)
obj = content_type.get_object_for_this_type(pk=object_id) obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDoesNotExist, ValueError): except (ObjectDoesNotExist, ValueError):
raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") % raise Http404(
{'ct_id': content_type_id, 'obj_id': object_id}) _("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id}
)
try: try:
get_absolute_url = obj.get_absolute_url get_absolute_url = obj.get_absolute_url
except AttributeError: except AttributeError:
raise http.Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") % raise Http404(
{'ct_name': content_type.name}) _("%(ct_name)s objects don't have a get_absolute_url() method") %
{'ct_name': content_type.name}
)
absurl = get_absolute_url() absurl = get_absolute_url()
# Try to figure out the object's domain, so we can do a cross-site redirect # Try to figure out the object's domain, so we can do a cross-site redirect
@ -33,7 +39,7 @@ def shortcut(request, content_type_id, object_id):
# If the object actually defines a domain, we're done. # If the object actually defines a domain, we're done.
if absurl.startswith(('http://', 'https://', '//')): if absurl.startswith(('http://', 'https://', '//')):
return http.HttpResponseRedirect(absurl) return HttpResponseRedirect(absurl)
# Otherwise, we need to introspect the object's relationships for a # Otherwise, we need to introspect the object's relationships for a
# relation to the Site object # relation to the Site object
@ -84,7 +90,6 @@ def shortcut(request, content_type_id, object_id):
# to whatever get_absolute_url() returned. # to whatever get_absolute_url() returned.
if object_domain is not None: if object_domain is not None:
protocol = request.scheme protocol = request.scheme
return http.HttpResponseRedirect('%s://%s%s' return HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl))
% (protocol, object_domain, absurl))
else: else:
return http.HttpResponseRedirect(absurl) return HttpResponseRedirect(absurl)

View File

@ -1,16 +1,16 @@
from django import http
from django.apps import apps from django.apps import apps
from django.conf import settings from django.conf import settings
from django.contrib.redirects.models import Redirect from django.contrib.redirects.models import Redirect
from django.contrib.sites.shortcuts import get_current_site from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseGone, HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
class RedirectFallbackMiddleware(MiddlewareMixin): class RedirectFallbackMiddleware(MiddlewareMixin):
# Defined as class-level attributes to be subclassing-friendly. # Defined as class-level attributes to be subclassing-friendly.
response_gone_class = http.HttpResponseGone response_gone_class = HttpResponseGone
response_redirect_class = http.HttpResponsePermanentRedirect response_redirect_class = HttpResponsePermanentRedirect
def __init__(self, get_response=None): def __init__(self, get_response=None):
if not apps.is_installed('django.contrib.sites'): if not apps.is_installed('django.contrib.sites'):

View File

@ -3,10 +3,10 @@ import codecs
import re import re
from io import BytesIO from io import BytesIO
from django import http
from django.conf import settings from django.conf import settings
from django.core import signals from django.core import signals
from django.core.handlers import base from django.core.handlers import base
from django.http import HttpRequest, QueryDict, parse_cookie
from django.urls import set_script_prefix from django.urls import set_script_prefix
from django.utils.encoding import force_text, repercent_broken_unicode from django.utils.encoding import force_text, repercent_broken_unicode
from django.utils.functional import cached_property from django.utils.functional import cached_property
@ -63,7 +63,7 @@ class LimitedStream:
return line return line
class WSGIRequest(http.HttpRequest): class WSGIRequest(HttpRequest):
def __init__(self, environ): def __init__(self, environ):
script_name = get_script_name(environ) script_name = get_script_name(environ)
path_info = get_path_info(environ) path_info = get_path_info(environ)
@ -108,7 +108,7 @@ class WSGIRequest(http.HttpRequest):
def GET(self): def GET(self):
# The WSGI spec says 'QUERY_STRING' may be absent. # The WSGI spec says 'QUERY_STRING' may be absent.
raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '') raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
return http.QueryDict(raw_query_string, encoding=self._encoding) return QueryDict(raw_query_string, encoding=self._encoding)
def _get_post(self): def _get_post(self):
if not hasattr(self, '_post'): if not hasattr(self, '_post'):
@ -121,7 +121,7 @@ class WSGIRequest(http.HttpRequest):
@cached_property @cached_property
def COOKIES(self): def COOKIES(self):
raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '') raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '')
return http.parse_cookie(raw_cookie) return parse_cookie(raw_cookie)
@property @property
def FILES(self): def FILES(self):

View File

@ -2,10 +2,10 @@ import re
import warnings import warnings
from urllib.parse import urlparse from urllib.parse import urlparse
from django import http
from django.conf import settings from django.conf import settings
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.core.mail import mail_managers from django.core.mail import mail_managers
from django.http import HttpResponsePermanentRedirect
from django.urls import is_valid_path from django.urls import is_valid_path
from django.utils.cache import ( from django.utils.cache import (
cc_delim_re, get_conditional_response, set_response_etag, cc_delim_re, get_conditional_response, set_response_etag,
@ -38,7 +38,7 @@ class CommonMiddleware(MiddlewareMixin):
ConditionalGetMiddleware. ConditionalGetMiddleware.
""" """
response_redirect_class = http.HttpResponsePermanentRedirect response_redirect_class = HttpResponsePermanentRedirect
def process_request(self, request): def process_request(self, request):
""" """

View File

@ -1,4 +1,7 @@
from django import http from django.http import (
HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound,
HttpResponseServerError,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.views.decorators.csrf import requires_csrf_token from django.views.decorators.csrf import requires_csrf_token
@ -52,7 +55,7 @@ def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
'<p>The requested URL {{ request_path }} was not found on this server.</p>') '<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(Context(context)) body = template.render(Context(context))
content_type = 'text/html' content_type = 'text/html'
return http.HttpResponseNotFound(body, content_type=content_type) return HttpResponseNotFound(body, content_type=content_type)
@requires_csrf_token @requires_csrf_token
@ -69,8 +72,8 @@ def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
if template_name != ERROR_500_TEMPLATE_NAME: if template_name != ERROR_500_TEMPLATE_NAME:
# Reraise if it's a missing custom template. # Reraise if it's a missing custom template.
raise raise
return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return http.HttpResponseServerError(template.render()) return HttpResponseServerError(template.render())
@requires_csrf_token @requires_csrf_token
@ -87,9 +90,9 @@ def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
if template_name != ERROR_400_TEMPLATE_NAME: if template_name != ERROR_400_TEMPLATE_NAME:
# Reraise if it's a missing custom template. # Reraise if it's a missing custom template.
raise raise
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') return HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
# No exception content is passed to the template, to not disclose any sensitive information. # No exception content is passed to the template, to not disclose any sensitive information.
return http.HttpResponseBadRequest(template.render()) return HttpResponseBadRequest(template.render())
# This can be called when CsrfViewMiddleware.process_view has not run, # This can be called when CsrfViewMiddleware.process_view has not run,
@ -112,7 +115,7 @@ def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME)
if template_name != ERROR_403_TEMPLATE_NAME: if template_name != ERROR_403_TEMPLATE_NAME:
# Reraise if it's a missing custom template. # Reraise if it's a missing custom template.
raise raise
return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
return http.HttpResponseForbidden( return HttpResponseForbidden(
template.render(request=request, context={'exception': force_text(exception)}) template.render(request=request, context={'exception': force_text(exception)})
) )

View File

@ -1,8 +1,11 @@
import logging import logging
from functools import update_wrapper from functools import update_wrapper
from django import http
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.http import (
HttpResponse, HttpResponseGone, HttpResponseNotAllowed,
HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse from django.urls import NoReverseMatch, reverse
from django.utils.decorators import classonlymethod from django.utils.decorators import classonlymethod
@ -89,13 +92,13 @@ class View:
'Method Not Allowed (%s): %s', request.method, request.path, 'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request} extra={'status_code': 405, 'request': request}
) )
return http.HttpResponseNotAllowed(self._allowed_methods()) return HttpResponseNotAllowed(self._allowed_methods())
def options(self, request, *args, **kwargs): def options(self, request, *args, **kwargs):
""" """
Handles responding to requests for the OPTIONS HTTP verb. Handles responding to requests for the OPTIONS HTTP verb.
""" """
response = http.HttpResponse() response = HttpResponse()
response['Allow'] = ', '.join(self._allowed_methods()) response['Allow'] = ', '.join(self._allowed_methods())
response['Content-Length'] = '0' response['Content-Length'] = '0'
return response return response
@ -187,15 +190,15 @@ class RedirectView(View):
url = self.get_redirect_url(*args, **kwargs) url = self.get_redirect_url(*args, **kwargs)
if url: if url:
if self.permanent: if self.permanent:
return http.HttpResponsePermanentRedirect(url) return HttpResponsePermanentRedirect(url)
else: else:
return http.HttpResponseRedirect(url) return HttpResponseRedirect(url)
else: else:
logger.warning( logger.warning(
'Gone: %s', request.path, 'Gone: %s', request.path,
extra={'status_code': 410, 'request': request} extra={'status_code': 410, 'request': request}
) )
return http.HttpResponseGone() return HttpResponseGone()
def head(self, request, *args, **kwargs): def head(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs) return self.get(request, *args, **kwargs)

View File

@ -3,9 +3,9 @@ import json
import os import os
from urllib.parse import unquote from urllib.parse import unquote
from django import http
from django.apps import apps from django.apps import apps
from django.conf import settings from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template import Context, Engine from django.template import Context, Engine
from django.urls import translate_url from django.urls import translate_url
from django.utils.encoding import force_text from django.utils.encoding import force_text
@ -39,14 +39,14 @@ def set_language(request):
next = unquote(next) # HTTP_REFERER may be encoded. next = unquote(next) # HTTP_REFERER may be encoded.
if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()): if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
next = '/' next = '/'
response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204) response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
if request.method == 'POST': if request.method == 'POST':
lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
if lang_code and check_for_language(lang_code): if lang_code and check_for_language(lang_code):
if next: if next:
next_trans = translate_url(next, lang_code) next_trans = translate_url(next, lang_code)
if next_trans != next: if next_trans != next:
response = http.HttpResponseRedirect(next_trans) response = HttpResponseRedirect(next_trans)
if hasattr(request, 'session'): if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code request.session[LANGUAGE_SESSION_KEY] = lang_code
else: else:
@ -202,7 +202,7 @@ def render_javascript_catalog(catalog=None, plural=None):
'plural': plural, 'plural': plural,
}) })
return http.HttpResponse(template.render(context), 'text/javascript') return HttpResponse(template.render(context), 'text/javascript')
def null_javascript_catalog(request, domain=None, packages=None): def null_javascript_catalog(request, domain=None, packages=None):
@ -298,7 +298,7 @@ class JavaScriptCatalog(View):
) if context['catalog'] else None ) if context['catalog'] else None
context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2)) context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2))
return http.HttpResponse(template.render(Context(context)), 'text/javascript') return HttpResponse(template.render(Context(context)), 'text/javascript')
class JSONCatalog(JavaScriptCatalog): class JSONCatalog(JavaScriptCatalog):
@ -319,4 +319,4 @@ class JSONCatalog(JavaScriptCatalog):
} }
""" """
def render_to_response(self, context, **response_kwargs): def render_to_response(self, context, **response_kwargs):
return http.JsonResponse(context) return JsonResponse(context)

View File

@ -1829,12 +1829,12 @@ preference persist in future requests.
If you are not using sessions, the language will persist in a cookie, whose name If you are not using sessions, the language will persist in a cookie, whose name
is configured in :setting:`LANGUAGE_COOKIE_NAME`. For example:: is configured in :setting:`LANGUAGE_COOKIE_NAME`. For example::
from django.utils import translation
from django import http
from django.conf import settings from django.conf import settings
from django.http import HttpResponse
from django.utils import translation
user_language = 'fr' user_language = 'fr'
translation.activate(user_language) translation.activate(user_language)
response = http.HttpResponse(...) response = HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
Using translations outside views and templates Using translations outside views and templates

View File

@ -1,9 +1,9 @@
from django import http
from django.contrib.messages import constants, get_level, set_level, utils from django.contrib.messages import constants, get_level, set_level, utils
from django.contrib.messages.api import MessageFailure from django.contrib.messages.api import MessageFailure
from django.contrib.messages.constants import DEFAULT_LEVELS from django.contrib.messages.constants import DEFAULT_LEVELS
from django.contrib.messages.storage import base, default_storage from django.contrib.messages.storage import base, default_storage
from django.contrib.messages.storage.base import Message from django.contrib.messages.storage.base import Message
from django.http import HttpRequest, HttpResponse
from django.test import modify_settings, override_settings from django.test import modify_settings, override_settings
from django.urls import reverse from django.urls import reverse
from django.utils.translation import gettext_lazy from django.utils.translation import gettext_lazy
@ -70,10 +70,10 @@ class BaseTests:
self.settings_override.disable() self.settings_override.disable()
def get_request(self): def get_request(self):
return http.HttpRequest() return HttpRequest()
def get_response(self): def get_response(self):
return http.HttpResponse() return HttpResponse()
def get_storage(self, data=None): def get_storage(self, data=None):
""" """

View File

@ -1,7 +1,7 @@
import unittest import unittest
from django import http
from django.contrib.messages.middleware import MessageMiddleware from django.contrib.messages.middleware import MessageMiddleware
from django.http import HttpRequest, HttpResponse
class MiddlewareTests(unittest.TestCase): class MiddlewareTests(unittest.TestCase):
@ -13,6 +13,6 @@ class MiddlewareTests(unittest.TestCase):
""" """
MessageMiddleware is tolerant of messages not existing on request. MessageMiddleware is tolerant of messages not existing on request.
""" """
request = http.HttpRequest() request = HttpRequest()
response = http.HttpResponse() response = HttpResponse()
self.middleware.process_response(request, response) self.middleware.process_response(request, response)

View File

@ -1,11 +1,11 @@
from django import http
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.template import engines from django.template import engines
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
def normal_view(request): def normal_view(request):
return http.HttpResponse('OK') return HttpResponse('OK')
def template_response(request): def template_response(request):
@ -19,7 +19,7 @@ def template_response_error(request):
def not_found(request): def not_found(request):
raise http.Http404() raise Http404()
def server_error(request): def server_error(request):
@ -35,7 +35,7 @@ def permission_denied(request):
def exception_in_render(request): def exception_in_render(request):
class CustomHttpResponse(http.HttpResponse): class CustomHttpResponse(HttpResponse):
def render(self): def render(self):
raise Exception('Exception in HttpResponse.render()') raise Exception('Exception in HttpResponse.render()')

View File

@ -1,9 +1,9 @@
from django import http
from django.conf import settings from django.conf import settings
from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.redirects.middleware import RedirectFallbackMiddleware
from django.contrib.redirects.models import Redirect from django.contrib.redirects.models import Redirect
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.http import HttpResponseForbidden, HttpResponseRedirect
from django.test import TestCase, modify_settings, override_settings from django.test import TestCase, modify_settings, override_settings
@ -49,8 +49,8 @@ class RedirectTests(TestCase):
class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware):
# Use HTTP responses different from the defaults # Use HTTP responses different from the defaults
response_gone_class = http.HttpResponseForbidden response_gone_class = HttpResponseForbidden
response_redirect_class = http.HttpResponseRedirect response_redirect_class = HttpResponseRedirect
@modify_settings(MIDDLEWARE={'append': 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'}) @modify_settings(MIDDLEWARE={'append': 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'})