diff options
Diffstat (limited to 'lib/python2.7/site-packages/django/middleware')
10 files changed, 0 insertions, 863 deletions
diff --git a/lib/python2.7/site-packages/django/middleware/__init__.py b/lib/python2.7/site-packages/django/middleware/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/lib/python2.7/site-packages/django/middleware/__init__.py +++ /dev/null diff --git a/lib/python2.7/site-packages/django/middleware/cache.py b/lib/python2.7/site-packages/django/middleware/cache.py deleted file mode 100644 index 7bbc167..0000000 --- a/lib/python2.7/site-packages/django/middleware/cache.py +++ /dev/null @@ -1,213 +0,0 @@ -""" -Cache middleware. If enabled, each Django-powered page will be cached based on -URL. The canonical way to enable cache middleware is to set -``UpdateCacheMiddleware`` as your first piece of middleware, and -``FetchFromCacheMiddleware`` as the last:: - - MIDDLEWARE_CLASSES = [ - 'django.middleware.cache.UpdateCacheMiddleware', - ... - 'django.middleware.cache.FetchFromCacheMiddleware' - ] - -This is counter-intuitive, but correct: ``UpdateCacheMiddleware`` needs to run -last during the response phase, which processes middleware bottom-up; -``FetchFromCacheMiddleware`` needs to run last during the request phase, which -processes middleware top-down. - -The single-class ``CacheMiddleware`` can be used for some simple sites. -However, if any other piece of middleware needs to affect the cache key, you'll -need to use the two-part ``UpdateCacheMiddleware`` and -``FetchFromCacheMiddleware``. This'll most often happen when you're using -Django's ``LocaleMiddleware``. - -More details about how the caching works: - -* Only GET or HEAD-requests with status code 200 are cached. - -* The number of seconds each page is stored for is set by the "max-age" section - of the response's "Cache-Control" header, falling back to the - CACHE_MIDDLEWARE_SECONDS setting if the section was not found. - -* This middleware expects that a HEAD request is answered with the same response - headers exactly like the corresponding GET request. - -* When a hit occurs, a shallow copy of the original response object is returned - from process_request. - -* Pages will be cached based on the contents of the request headers listed in - the response's "Vary" header. - -* This middleware also sets ETag, Last-Modified, Expires and Cache-Control - headers on the response object. - -""" - -import warnings - -from django.conf import settings -from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS -from django.utils.cache import (get_cache_key, get_max_age, has_vary_header, - learn_cache_key, patch_response_headers) - - -class UpdateCacheMiddleware(object): - """ - Response-phase cache middleware that updates the cache if the response is - cacheable. - - Must be used as part of the two-part update/fetch cache middleware. - UpdateCacheMiddleware must be the first piece of middleware in - MIDDLEWARE_CLASSES so that it'll get called last during the response phase. - """ - def __init__(self): - self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS - self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX - self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) - self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS - self.cache = get_cache(self.cache_alias) - - def _session_accessed(self, request): - try: - return request.session.accessed - except AttributeError: - return False - - def _should_update_cache(self, request, response): - if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: - return False - # If the session has not been accessed otherwise, we don't want to - # cause it to be accessed here. If it hasn't been accessed, then the - # user's logged-in status has not affected the response anyway. - if self.cache_anonymous_only and self._session_accessed(request): - assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." - if request.user.is_authenticated(): - # Don't cache user-variable requests from authenticated users. - return False - return True - - def process_response(self, request, response): - """Sets the cache, if needed.""" - if not self._should_update_cache(request, response): - # We don't need to update the cache, just return. - return response - - if response.streaming or response.status_code != 200: - return response - - # Don't cache responses that set a user-specific (and maybe security - # sensitive) cookie in response to a cookie-less request. - if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'): - return response - - # Try to get the timeout from the "max-age" section of the "Cache- - # Control" header before reverting to using the default cache_timeout - # length. - timeout = get_max_age(response) - if timeout == None: - timeout = self.cache_timeout - elif timeout == 0: - # max-age was set to 0, don't bother caching. - return response - patch_response_headers(response, timeout) - if timeout: - cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache) - if hasattr(response, 'render') and callable(response.render): - response.add_post_render_callback( - lambda r: self.cache.set(cache_key, r, timeout) - ) - else: - self.cache.set(cache_key, response, timeout) - return response - -class FetchFromCacheMiddleware(object): - """ - Request-phase cache middleware that fetches a page from the cache. - - Must be used as part of the two-part update/fetch cache middleware. - FetchFromCacheMiddleware must be the last piece of middleware in - MIDDLEWARE_CLASSES so that it'll get called last during the request phase. - """ - def __init__(self): - self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS - self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX - self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS - self.cache = get_cache(self.cache_alias) - - def process_request(self, request): - """ - Checks whether the page is already cached and returns the cached - version if available. - """ - if not request.method in ('GET', 'HEAD'): - request._cache_update_cache = False - return None # Don't bother checking the cache. - - # try and get the cached GET response - cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) - if cache_key is None: - request._cache_update_cache = True - return None # No cache information available, need to rebuild. - response = self.cache.get(cache_key, None) - # if it wasn't found and we are looking for a HEAD, try looking just for that - if response is None and request.method == 'HEAD': - cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) - response = self.cache.get(cache_key, None) - - if response is None: - request._cache_update_cache = True - return None # No cache information available, need to rebuild. - - # hit, return cached response - request._cache_update_cache = False - return response - -class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware): - """ - Cache middleware that provides basic behavior for many simple sites. - - Also used as the hook point for the cache decorator, which is generated - using the decorator-from-middleware utility. - """ - def __init__(self, cache_timeout=None, cache_anonymous_only=None, **kwargs): - # We need to differentiate between "provided, but using default value", - # and "not provided". If the value is provided using a default, then - # we fall back to system defaults. If it is not provided at all, - # we need to use middleware defaults. - - cache_kwargs = {} - - try: - self.key_prefix = kwargs['key_prefix'] - if self.key_prefix is not None: - cache_kwargs['KEY_PREFIX'] = self.key_prefix - else: - self.key_prefix = '' - except KeyError: - self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX - cache_kwargs['KEY_PREFIX'] = self.key_prefix - - try: - self.cache_alias = kwargs['cache_alias'] - if self.cache_alias is None: - self.cache_alias = DEFAULT_CACHE_ALIAS - if cache_timeout is not None: - cache_kwargs['TIMEOUT'] = cache_timeout - except KeyError: - self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS - if cache_timeout is None: - cache_kwargs['TIMEOUT'] = settings.CACHE_MIDDLEWARE_SECONDS - else: - cache_kwargs['TIMEOUT'] = cache_timeout - - if cache_anonymous_only is None: - self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) - else: - self.cache_anonymous_only = cache_anonymous_only - - if self.cache_anonymous_only: - msg = "CACHE_MIDDLEWARE_ANONYMOUS_ONLY has been deprecated and will be removed in Django 1.8." - warnings.warn(msg, PendingDeprecationWarning, stacklevel=1) - - self.cache = get_cache(self.cache_alias, **cache_kwargs) - self.cache_timeout = self.cache.default_timeout diff --git a/lib/python2.7/site-packages/django/middleware/clickjacking.py b/lib/python2.7/site-packages/django/middleware/clickjacking.py deleted file mode 100644 index 81763ef..0000000 --- a/lib/python2.7/site-packages/django/middleware/clickjacking.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -Clickjacking Protection Middleware. - -This module provides a middleware that implements protection against a -malicious site loading resources from your site in a hidden frame. -""" - -from django.conf import settings - -class XFrameOptionsMiddleware(object): - """ - Middleware that sets the X-Frame-Options HTTP header in HTTP responses. - - Does not set the header if it's already set or if the response contains - a xframe_options_exempt value set to True. - - By default, sets the X-Frame-Options header to 'SAMEORIGIN', meaning the - response can only be loaded on a frame within the same site. To prevent the - response from being loaded in a frame in any site, set X_FRAME_OPTIONS in - your project's Django settings to 'DENY'. - - Note: older browsers will quietly ignore this header, thus other - clickjacking protection techniques should be used if protection in those - browsers is required. - - http://en.wikipedia.org/wiki/Clickjacking#Server_and_client - """ - def process_response(self, request, response): - # Don't set it if it's already in the response - if response.get('X-Frame-Options', None) is not None: - return response - - # Don't set it if they used @xframe_options_exempt - if getattr(response, 'xframe_options_exempt', False): - return response - - response['X-Frame-Options'] = self.get_xframe_options_value(request, - response) - return response - - def get_xframe_options_value(self, request, response): - """ - Gets the value to set for the X_FRAME_OPTIONS header. - - By default this uses the value from the X_FRAME_OPTIONS Django - settings. If not found in settings, defaults to 'SAMEORIGIN'. - - This method can be overridden if needed, allowing it to vary based on - the request or response. - """ - return getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper() diff --git a/lib/python2.7/site-packages/django/middleware/common.py b/lib/python2.7/site-packages/django/middleware/common.py deleted file mode 100644 index 2c76c47..0000000 --- a/lib/python2.7/site-packages/django/middleware/common.py +++ /dev/null @@ -1,174 +0,0 @@ -import hashlib -import logging -import re -import warnings - -from django.conf import settings -from django.core.mail import mail_managers -from django.core import urlresolvers -from django import http -from django.utils.encoding import force_text -from django.utils.http import urlquote -from django.utils import six - - -logger = logging.getLogger('django.request') - - -class CommonMiddleware(object): - """ - "Common" middleware for taking care of some basic operations: - - - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - - - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, - this middleware appends missing slashes and/or prepends missing - "www."s. - - - If APPEND_SLASH is set and the initial URL doesn't end with a - slash, and it is not found in urlpatterns, a new URL is formed by - appending a slash at the end. If this new URL is found in - urlpatterns, then an HTTP-redirect is returned to this new URL; - otherwise the initial URL is processed as usual. - - - ETags: If the USE_ETAGS setting is set, ETags will be calculated from - the entire page content and Not Modified responses will be returned - appropriately. - """ - - def process_request(self, request): - """ - Check for denied User-Agents and rewrite the URL based on - settings.APPEND_SLASH and settings.PREPEND_WWW - """ - - # Check for denied User-Agents - if 'HTTP_USER_AGENT' in request.META: - for user_agent_regex in settings.DISALLOWED_USER_AGENTS: - if user_agent_regex.search(request.META['HTTP_USER_AGENT']): - logger.warning('Forbidden (User agent): %s', request.path, - extra={ - 'status_code': 403, - 'request': request - } - ) - return http.HttpResponseForbidden('<h1>Forbidden</h1>') - - # Check for a redirect based on settings.APPEND_SLASH - # and settings.PREPEND_WWW - host = request.get_host() - old_url = [host, request.path] - new_url = old_url[:] - - if (settings.PREPEND_WWW and old_url[0] and - not old_url[0].startswith('www.')): - new_url[0] = 'www.' + old_url[0] - - # Append a slash if APPEND_SLASH is set and the URL doesn't have a - # trailing slash and there is no pattern for the current path - if settings.APPEND_SLASH and (not old_url[1].endswith('/')): - urlconf = getattr(request, 'urlconf', None) - if (not urlresolvers.is_valid_path(request.path_info, urlconf) and - urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)): - new_url[1] = new_url[1] + '/' - if settings.DEBUG and request.method == 'POST': - raise RuntimeError(("" - "You called this URL via POST, but the URL doesn't end " - "in a slash and you have APPEND_SLASH set. Django can't " - "redirect to the slash URL while maintaining POST data. " - "Change your form to point to %s%s (note the trailing " - "slash), or set APPEND_SLASH=False in your Django " - "settings.") % (new_url[0], new_url[1])) - - if new_url == old_url: - # No redirects required. - return - if new_url[0]: - newurl = "%s://%s%s" % ( - 'https' if request.is_secure() else 'http', - new_url[0], urlquote(new_url[1])) - else: - newurl = urlquote(new_url[1]) - if request.META.get('QUERY_STRING', ''): - if six.PY3: - newurl += '?' + request.META['QUERY_STRING'] - else: - # `query_string` is a bytestring. Appending it to the unicode - # string `newurl` will fail if it isn't ASCII-only. This isn't - # allowed; only broken software generates such query strings. - # Better drop the invalid query string than crash (#15152). - try: - newurl += '?' + request.META['QUERY_STRING'].decode() - except UnicodeDecodeError: - pass - return http.HttpResponsePermanentRedirect(newurl) - - def process_response(self, request, response): - """ - Calculate the ETag, if needed. - """ - if settings.SEND_BROKEN_LINK_EMAILS: - warnings.warn("SEND_BROKEN_LINK_EMAILS is deprecated. " - "Use BrokenLinkEmailsMiddleware instead.", - PendingDeprecationWarning, stacklevel=2) - BrokenLinkEmailsMiddleware().process_response(request, response) - - if settings.USE_ETAGS: - if response.has_header('ETag'): - etag = response['ETag'] - elif response.streaming: - etag = None - else: - etag = '"%s"' % hashlib.md5(response.content).hexdigest() - if etag is not None: - if (200 <= response.status_code < 300 - and request.META.get('HTTP_IF_NONE_MATCH') == etag): - cookies = response.cookies - response = http.HttpResponseNotModified() - response.cookies = cookies - else: - response['ETag'] = etag - - return response - - -class BrokenLinkEmailsMiddleware(object): - - def process_response(self, request, response): - """ - Send broken link emails for relevant 404 NOT FOUND responses. - """ - if response.status_code == 404 and not settings.DEBUG: - domain = request.get_host() - path = request.get_full_path() - referer = force_text(request.META.get('HTTP_REFERER', ''), errors='replace') - - if not self.is_ignorable_request(request, path, domain, referer): - ua = request.META.get('HTTP_USER_AGENT', '<none>') - ip = request.META.get('REMOTE_ADDR', '<none>') - mail_managers( - "Broken %slink on %s" % ( - ('INTERNAL ' if self.is_internal_request(domain, referer) else ''), - domain - ), - "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" - "IP address: %s\n" % (referer, path, ua, ip), - fail_silently=True) - return response - - def is_internal_request(self, domain, referer): - """ - Returns True if the referring URL is the same domain as the current request. - """ - # Different subdomains are treated as different domains. - return bool(re.match("^https?://%s/" % re.escape(domain), referer)) - - def is_ignorable_request(self, request, uri, domain, referer): - """ - Returns True if the given request *shouldn't* notify the site managers. - """ - # '?' in referer is identified as search engine source - if (not referer or - (not self.is_internal_request(domain, referer) and '?' in referer)): - return True - return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS) diff --git a/lib/python2.7/site-packages/django/middleware/csrf.py b/lib/python2.7/site-packages/django/middleware/csrf.py deleted file mode 100644 index 1089153..0000000 --- a/lib/python2.7/site-packages/django/middleware/csrf.py +++ /dev/null @@ -1,208 +0,0 @@ -""" -Cross Site Request Forgery Middleware. - -This module provides a middleware that implements protection -against request forgeries from other sites. -""" -from __future__ import unicode_literals - -import logging -import re - -from django.conf import settings -from django.core.urlresolvers import get_callable -from django.utils.cache import patch_vary_headers -from django.utils.encoding import force_text -from django.utils.http import same_origin -from django.utils.crypto import constant_time_compare, get_random_string - - -logger = logging.getLogger('django.request') - -REASON_NO_REFERER = "Referer checking failed - no Referer." -REASON_BAD_REFERER = "Referer checking failed - %s does not match %s." -REASON_NO_CSRF_COOKIE = "CSRF cookie not set." -REASON_BAD_TOKEN = "CSRF token missing or incorrect." - -CSRF_KEY_LENGTH = 32 - -def _get_failure_view(): - """ - Returns the view to be used for CSRF rejections - """ - return get_callable(settings.CSRF_FAILURE_VIEW) - - -def _get_new_csrf_key(): - return get_random_string(CSRF_KEY_LENGTH) - - -def get_token(request): - """ - Returns the CSRF token required for a POST form. The token is an - alphanumeric value. - - A side effect of calling this function is to make the csrf_protect - decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie' - header to the outgoing response. For this reason, you may need to use this - function lazily, as is done by the csrf context processor. - """ - request.META["CSRF_COOKIE_USED"] = True - return request.META.get("CSRF_COOKIE", None) - - -def rotate_token(request): - """ - Changes the CSRF token in use for a request - should be done on login - for security purposes. - """ - request.META.update({ - "CSRF_COOKIE_USED": True, - "CSRF_COOKIE": _get_new_csrf_key(), - }) - - -def _sanitize_token(token): - # Allow only alphanum - if len(token) > CSRF_KEY_LENGTH: - return _get_new_csrf_key() - token = re.sub('[^a-zA-Z0-9]+', '', force_text(token)) - if token == "": - # In case the cookie has been truncated to nothing at some point. - return _get_new_csrf_key() - return token - - -class CsrfViewMiddleware(object): - """ - Middleware that requires a present and correct csrfmiddlewaretoken - for POST requests that have a CSRF cookie, and sets an outgoing - CSRF cookie. - - This middleware should be used in conjunction with the csrf_token template - tag. - """ - # The _accept and _reject methods currently only exist for the sake of the - # requires_csrf_token decorator. - def _accept(self, request): - # Avoid checking the request twice by adding a custom attribute to - # request. This will be relevant when both decorator and middleware - # are used. - request.csrf_processing_done = True - return None - - def _reject(self, request, reason): - logger.warning('Forbidden (%s): %s', - reason, request.path, - extra={ - 'status_code': 403, - 'request': request, - } - ) - return _get_failure_view()(request, reason=reason) - - def process_view(self, request, callback, callback_args, callback_kwargs): - - if getattr(request, 'csrf_processing_done', False): - return None - - try: - csrf_token = _sanitize_token( - request.COOKIES[settings.CSRF_COOKIE_NAME]) - # Use same token next time - request.META['CSRF_COOKIE'] = csrf_token - except KeyError: - csrf_token = None - # Generate token and store it in the request, so it's - # available to the view. - request.META["CSRF_COOKIE"] = _get_new_csrf_key() - - # Wait until request.META["CSRF_COOKIE"] has been manipulated before - # bailing out, so that get_token still works - if getattr(callback, 'csrf_exempt', False): - return None - - # Assume that anything not defined as 'safe' by RFC2616 needs protection - if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): - if getattr(request, '_dont_enforce_csrf_checks', False): - # Mechanism to turn off CSRF checks for test suite. - # It comes after the creation of CSRF cookies, so that - # everything else continues to work exactly the same - # (e.g. cookies are sent, etc.), but before any - # branches that call reject(). - return self._accept(request) - - if request.is_secure(): - # Suppose user visits http://example.com/ - # An active network attacker (man-in-the-middle, MITM) sends a - # POST form that targets https://example.com/detonate-bomb/ and - # submits it via JavaScript. - # - # The attacker will need to provide a CSRF cookie and token, but - # that's no problem for a MITM and the session-independent - # nonce we're using. So the MITM can circumvent the CSRF - # protection. This is true for any HTTP connection, but anyone - # using HTTPS expects better! For this reason, for - # https://example.com/ we need additional protection that treats - # http://example.com/ as completely untrusted. Under HTTPS, - # Barth et al. found that the Referer header is missing for - # same-domain requests in only about 0.2% of cases or less, so - # we can use strict Referer checking. - referer = request.META.get('HTTP_REFERER') - if referer is None: - return self._reject(request, REASON_NO_REFERER) - - # Note that request.get_host() includes the port. - good_referer = 'https://%s/' % request.get_host() - if not same_origin(referer, good_referer): - reason = REASON_BAD_REFERER % (referer, good_referer) - return self._reject(request, reason) - - if csrf_token is None: - # No CSRF cookie. For POST requests, we insist on a CSRF cookie, - # and in this way we can avoid all CSRF attacks, including login - # CSRF. - return self._reject(request, REASON_NO_CSRF_COOKIE) - - # Check non-cookie token for match. - request_csrf_token = "" - if request.method == "POST": - request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') - - if request_csrf_token == "": - # Fall back to X-CSRFToken, to make things easier for AJAX, - # and possible for PUT/DELETE. - request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') - - if not constant_time_compare(request_csrf_token, csrf_token): - return self._reject(request, REASON_BAD_TOKEN) - - return self._accept(request) - - def process_response(self, request, response): - if getattr(response, 'csrf_processing_done', False): - return response - - # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was - # never called, probaby because a request middleware returned a response - # (for example, contrib.auth redirecting to a login page). - if request.META.get("CSRF_COOKIE") is None: - return response - - if not request.META.get("CSRF_COOKIE_USED", False): - return response - - # Set the CSRF cookie even if it's already set, so we renew - # the expiry timer. - response.set_cookie(settings.CSRF_COOKIE_NAME, - request.META["CSRF_COOKIE"], - max_age = 60 * 60 * 24 * 7 * 52, - domain=settings.CSRF_COOKIE_DOMAIN, - path=settings.CSRF_COOKIE_PATH, - secure=settings.CSRF_COOKIE_SECURE, - httponly=settings.CSRF_COOKIE_HTTPONLY - ) - # Content varies with the CSRF cookie, so set the Vary header. - patch_vary_headers(response, ('Cookie',)) - response.csrf_processing_done = True - return response diff --git a/lib/python2.7/site-packages/django/middleware/doc.py b/lib/python2.7/site-packages/django/middleware/doc.py deleted file mode 100644 index 1af7b61..0000000 --- a/lib/python2.7/site-packages/django/middleware/doc.py +++ /dev/null @@ -1,6 +0,0 @@ -"""XViewMiddleware has been moved to django.contrib.admindocs.middleware.""" - -import warnings -warnings.warn(__doc__, PendingDeprecationWarning, stacklevel=2) - -from django.contrib.admindocs.middleware import XViewMiddleware diff --git a/lib/python2.7/site-packages/django/middleware/gzip.py b/lib/python2.7/site-packages/django/middleware/gzip.py deleted file mode 100644 index fb54501..0000000 --- a/lib/python2.7/site-packages/django/middleware/gzip.py +++ /dev/null @@ -1,52 +0,0 @@ -import re - -from django.utils.text import compress_sequence, compress_string -from django.utils.cache import patch_vary_headers - -re_accepts_gzip = re.compile(r'\bgzip\b') - -class GZipMiddleware(object): - """ - This middleware compresses content if the browser allows gzip compression. - It sets the Vary header accordingly, so that caches will base their storage - on the Accept-Encoding header. - """ - def process_response(self, request, response): - # It's not worth attempting to compress really short responses. - if not response.streaming and len(response.content) < 200: - return response - - patch_vary_headers(response, ('Accept-Encoding',)) - - # Avoid gzipping if we've already got a content-encoding. - if response.has_header('Content-Encoding'): - return response - - # MSIE have issues with gzipped response of various content types. - if "msie" in request.META.get('HTTP_USER_AGENT', '').lower(): - ctype = response.get('Content-Type', '').lower() - if not ctype.startswith("text/") or "javascript" in ctype: - return response - - ae = request.META.get('HTTP_ACCEPT_ENCODING', '') - if not re_accepts_gzip.search(ae): - return response - - if response.streaming: - # Delete the `Content-Length` header for streaming content, because - # we won't know the compressed size until we stream it. - response.streaming_content = compress_sequence(response.streaming_content) - del response['Content-Length'] - else: - # Return the compressed content only if it's actually shorter. - compressed_content = compress_string(response.content) - if len(compressed_content) >= len(response.content): - return response - response.content = compressed_content - response['Content-Length'] = str(len(response.content)) - - if response.has_header('ETag'): - response['ETag'] = re.sub('"$', ';gzip"', response['ETag']) - response['Content-Encoding'] = 'gzip' - - return response diff --git a/lib/python2.7/site-packages/django/middleware/http.py b/lib/python2.7/site-packages/django/middleware/http.py deleted file mode 100644 index 5a46e04..0000000 --- a/lib/python2.7/site-packages/django/middleware/http.py +++ /dev/null @@ -1,35 +0,0 @@ -from django.utils.http import http_date, parse_http_date_safe - -class ConditionalGetMiddleware(object): - """ - Handles conditional GET operations. If the response has a ETag or - Last-Modified header, and the request has If-None-Match or - If-Modified-Since, the response is replaced by an HttpNotModified. - - Also sets the Date and Content-Length response-headers. - """ - def process_response(self, request, response): - response['Date'] = http_date() - if not response.streaming and not response.has_header('Content-Length'): - response['Content-Length'] = str(len(response.content)) - - if response.has_header('ETag'): - if_none_match = request.META.get('HTTP_IF_NONE_MATCH') - if if_none_match == response['ETag']: - # Setting the status is enough here. The response handling path - # automatically removes content for this status code (in - # http.conditional_content_removal()). - response.status_code = 304 - - if response.has_header('Last-Modified'): - if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') - if if_modified_since is not None: - if_modified_since = parse_http_date_safe(if_modified_since) - if if_modified_since is not None: - last_modified = parse_http_date_safe(response['Last-Modified']) - if last_modified is not None and last_modified <= if_modified_since: - # Setting the status code is enough here (same reasons as - # above). - response.status_code = 304 - - return response diff --git a/lib/python2.7/site-packages/django/middleware/locale.py b/lib/python2.7/site-packages/django/middleware/locale.py deleted file mode 100644 index bd14910..0000000 --- a/lib/python2.7/site-packages/django/middleware/locale.py +++ /dev/null @@ -1,68 +0,0 @@ -"This is the locale selecting middleware that will look at accept headers" - -from django.conf import settings -from django.core.urlresolvers import (is_valid_path, get_resolver, - LocaleRegexURLResolver) -from django.http import HttpResponseRedirect -from django.utils.cache import patch_vary_headers -from django.utils import translation -from django.utils.datastructures import SortedDict - - -class LocaleMiddleware(object): - """ - This is a very simple middleware that parses a request - and decides what translation object to install in the current - thread context. This allows pages to be dynamically - translated to the language the user desires (if the language - is available, of course). - """ - - def __init__(self): - self._supported_languages = SortedDict(settings.LANGUAGES) - self._is_language_prefix_patterns_used = False - for url_pattern in get_resolver(None).url_patterns: - if isinstance(url_pattern, LocaleRegexURLResolver): - self._is_language_prefix_patterns_used = True - break - - def process_request(self, request): - check_path = self.is_language_prefix_patterns_used() - language = translation.get_language_from_request( - request, check_path=check_path) - translation.activate(language) - request.LANGUAGE_CODE = translation.get_language() - - def process_response(self, request, response): - language = translation.get_language() - language_from_path = translation.get_language_from_path( - request.path_info, supported=self._supported_languages - ) - if (response.status_code == 404 and not language_from_path - and self.is_language_prefix_patterns_used()): - urlconf = getattr(request, 'urlconf', None) - language_path = '/%s%s' % (language, request.path_info) - path_valid = is_valid_path(language_path, urlconf) - if (not path_valid and settings.APPEND_SLASH - and not language_path.endswith('/')): - path_valid = is_valid_path("%s/" % language_path, urlconf) - - if path_valid: - language_url = "%s://%s/%s%s" % ( - 'https' if request.is_secure() else 'http', - request.get_host(), language, request.get_full_path()) - return HttpResponseRedirect(language_url) - - if not (self.is_language_prefix_patterns_used() - and language_from_path): - patch_vary_headers(response, ('Accept-Language',)) - if 'Content-Language' not in response: - response['Content-Language'] = language - return response - - def is_language_prefix_patterns_used(self): - """ - Returns `True` if the `LocaleRegexURLResolver` is used - at root level of the urlpatterns, else it returns `False`. - """ - return self._is_language_prefix_patterns_used diff --git a/lib/python2.7/site-packages/django/middleware/transaction.py b/lib/python2.7/site-packages/django/middleware/transaction.py deleted file mode 100644 index 95cc9a2..0000000 --- a/lib/python2.7/site-packages/django/middleware/transaction.py +++ /dev/null @@ -1,56 +0,0 @@ -import warnings - -from django.core.exceptions import MiddlewareNotUsed -from django.db import connection, transaction - -class TransactionMiddleware(object): - """ - Transaction middleware. If this is enabled, each view function will be run - with commit_on_response activated - that way a save() doesn't do a direct - commit, the commit is done when a successful response is created. If an - exception happens, the database is rolled back. - """ - - def __init__(self): - warnings.warn( - "TransactionMiddleware is deprecated in favor of ATOMIC_REQUESTS.", - PendingDeprecationWarning, stacklevel=2) - if connection.settings_dict['ATOMIC_REQUESTS']: - raise MiddlewareNotUsed - - def process_request(self, request): - """Enters transaction management""" - transaction.enter_transaction_management() - - def process_exception(self, request, exception): - """Rolls back the database and leaves transaction management""" - if transaction.is_dirty(): - # This rollback might fail because of network failure for example. - # If rollback isn't possible it is impossible to clean the - # connection's state. So leave the connection in dirty state and - # let request_finished signal deal with cleaning the connection. - transaction.rollback() - transaction.leave_transaction_management() - - def process_response(self, request, response): - """Commits and leaves transaction management.""" - if not transaction.get_autocommit(): - if transaction.is_dirty(): - # Note: it is possible that the commit fails. If the reason is - # closed connection or some similar reason, then there is - # little hope to proceed nicely. However, in some cases ( - # deferred foreign key checks for exampl) it is still possible - # to rollback(). - try: - transaction.commit() - except Exception: - # If the rollback fails, the transaction state will be - # messed up. It doesn't matter, the connection will be set - # to clean state after the request finishes. And, we can't - # clean the state here properly even if we wanted to, the - # connection is in transaction but we can't rollback... - transaction.rollback() - transaction.leave_transaction_management() - raise - transaction.leave_transaction_management() - return response |