diff options
Diffstat (limited to 'parts/django/django/middleware')
-rw-r--r-- | parts/django/django/middleware/__init__.py | 0 | ||||
-rw-r--r-- | parts/django/django/middleware/cache.py | 156 | ||||
-rw-r--r-- | parts/django/django/middleware/common.py | 147 | ||||
-rw-r--r-- | parts/django/django/middleware/csrf.py | 298 | ||||
-rw-r--r-- | parts/django/django/middleware/doc.py | 19 | ||||
-rw-r--r-- | parts/django/django/middleware/gzip.py | 38 | ||||
-rw-r--r-- | parts/django/django/middleware/http.py | 51 | ||||
-rw-r--r-- | parts/django/django/middleware/locale.py | 25 | ||||
-rw-r--r-- | parts/django/django/middleware/transaction.py | 27 |
9 files changed, 761 insertions, 0 deletions
diff --git a/parts/django/django/middleware/__init__.py b/parts/django/django/middleware/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/parts/django/django/middleware/__init__.py diff --git a/parts/django/django/middleware/cache.py b/parts/django/django/middleware/cache.py new file mode 100644 index 0000000..3f602fe --- /dev/null +++ b/parts/django/django/middleware/cache.py @@ -0,0 +1,156 @@ +""" +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 parameter-less 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. + +* If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests + (i.e., those not made by a logged-in user) will be cached. This is a simple + and effective way of avoiding the caching of the Django admin (and any other + user-specific content). + +* This middleware expects that a HEAD request is answered with a response + 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. + +""" + +from django.conf import settings +from django.core.cache import cache +from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers, get_max_age + +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) + + def process_response(self, request, response): + """Sets the cache, if needed.""" + if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: + # We don't need to update the cache, just return. + return response + if request.method != 'GET': + # This is a stronger requirement than above. It is needed + # because of interactions between this middleware and the + # HTTPMiddleware, which throws the body of a HEAD-request + # away before this middleware gets a chance to cache it. + return response + if not response.status_code == 200: + 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.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_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) + + def process_request(self, request): + """ + Checks whether the page is already cached and returns the cached + version if available. + """ + if self.cache_anonymous_only: + 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 not request.method in ('GET', 'HEAD') or request.GET: + request._cache_update_cache = False + return None # Don't bother checking the cache. + + if self.cache_anonymous_only and request.user.is_authenticated(): + request._cache_update_cache = False + return None # Don't cache requests from authenticated users. + + cache_key = get_cache_key(request, self.key_prefix) + if cache_key is None: + request._cache_update_cache = True + return None # No cache information available, need to rebuild. + + response = cache.get(cache_key, None) + if response is None: + request._cache_update_cache = True + return None # No cache information available, need to rebuild. + + 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, key_prefix=None, cache_anonymous_only=None): + self.cache_timeout = cache_timeout + if cache_timeout is None: + self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS + self.key_prefix = key_prefix + if key_prefix is None: + self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX + 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 diff --git a/parts/django/django/middleware/common.py b/parts/django/django/middleware/common.py new file mode 100644 index 0000000..0be89d4 --- /dev/null +++ b/parts/django/django/middleware/common.py @@ -0,0 +1,147 @@ +import re + +from django.conf import settings +from django import http +from django.core.mail import mail_managers +from django.utils.http import urlquote +from django.core import urlresolvers +from django.utils.hashcompat import md5_constructor + +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']): + 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 _is_valid_path(request.path_info, urlconf) and + _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" % ( + request.is_secure() and 'https' or 'http', + new_url[0], urlquote(new_url[1])) + else: + newurl = urlquote(new_url[1]) + if request.GET: + newurl += '?' + request.META['QUERY_STRING'] + return http.HttpResponsePermanentRedirect(newurl) + + def process_response(self, request, response): + "Send broken link emails and calculate the Etag, if needed." + if response.status_code == 404: + if settings.SEND_BROKEN_LINK_EMAILS: + # If the referrer was from an internal link or a non-search-engine site, + # send a note to the managers. + domain = request.get_host() + referer = request.META.get('HTTP_REFERER', None) + is_internal = _is_internal_request(domain, referer) + path = request.get_full_path() + if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): + ua = request.META.get('HTTP_USER_AGENT', '<none>') + ip = request.META.get('REMOTE_ADDR', '<none>') + mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), + "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \ + % (referer, request.get_full_path(), ua, ip)) + return response + + # Use ETags, if requested. + if settings.USE_ETAGS: + if response.has_header('ETag'): + etag = response['ETag'] + else: + etag = '"%s"' % md5_constructor(response.content).hexdigest() + if response.status_code >= 200 and 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 + +def _is_ignorable_404(uri): + """ + Returns True if a 404 at the given URL *shouldn't* notify the site managers. + """ + for start in settings.IGNORABLE_404_STARTS: + if uri.startswith(start): + return True + for end in settings.IGNORABLE_404_ENDS: + if uri.endswith(end): + return True + return False + +def _is_internal_request(domain, referer): + """ + Returns true if the referring URL is the same domain as the current request. + """ + # Different subdomains are treated as different domains. + return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer) + +def _is_valid_path(path, urlconf=None): + """ + Returns True if the given path resolves against the default URL resolver, + False otherwise. + + This is a convenience method to make working with "is this a match?" cases + easier, avoiding unnecessarily indented try...except blocks. + """ + try: + urlresolvers.resolve(path, urlconf) + return True + except urlresolvers.Resolver404: + return False + diff --git a/parts/django/django/middleware/csrf.py b/parts/django/django/middleware/csrf.py new file mode 100644 index 0000000..67b02f0 --- /dev/null +++ b/parts/django/django/middleware/csrf.py @@ -0,0 +1,298 @@ +""" +Cross Site Request Forgery Middleware. + +This module provides a middleware that implements protection +against request forgeries from other sites. +""" + +import itertools +import re +import random + +from django.conf import settings +from django.core.urlresolvers import get_callable +from django.utils.cache import patch_vary_headers +from django.utils.hashcompat import md5_constructor +from django.utils.safestring import mark_safe + +_POST_FORM_RE = \ + re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) + +_HTML_TYPES = ('text/html', 'application/xhtml+xml') + +# Use the system (hardware-based) random number generator if it exists. +if hasattr(random, 'SystemRandom'): + randrange = random.SystemRandom().randrange +else: + randrange = random.randrange +_MAX_CSRF_KEY = 18446744073709551616L # 2 << 63 + +REASON_NO_REFERER = "Referer checking failed - no Referer." +REASON_BAD_REFERER = "Referer checking failed - %s does not match %s." +REASON_NO_COOKIE = "No CSRF or session cookie." +REASON_NO_CSRF_COOKIE = "CSRF cookie not set." +REASON_BAD_TOKEN = "CSRF token missing or incorrect." + + +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 md5_constructor("%s%s" + % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest() + + +def _make_legacy_session_token(session_id): + return md5_constructor(settings.SECRET_KEY + session_id).hexdigest() + + +def get_token(request): + """ + Returns the 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 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 _sanitize_token(token): + # Allow only alphanum, and ensure we return a 'str' for the sake of the post + # processing middleware. + token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore'))) + if token == "": + # In case the cookie has been truncated to nothing at some point. + return _get_new_csrf_key() + else: + 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): + 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 + + # If the user doesn't have a CSRF cookie, generate one and store it in the + # request, so it's available to the view. We'll store it in a cookie when + # we reach the response. + try: + # In case of cookies from untrusted sources, we strip anything + # dangerous at this point, so that the cookie + token will have the + # same, sanitized value. + request.META["CSRF_COOKIE"] = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME]) + cookie_is_new = False + except KeyError: + # No cookie, so create one. This will be sent with the next + # response. + request.META["CSRF_COOKIE"] = _get_new_csrf_key() + # Set a flag to allow us to fall back and allow the session id in + # place of a CSRF cookie for this request only. + cookie_is_new = True + + # 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 + + if request.method == 'POST': + 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 the + # any branches that call reject() + return self._accept(request) + + if request.is_ajax(): + # .is_ajax() is based on the presence of X-Requested-With. In + # the context of a browser, this can only be sent if using + # XmlHttpRequest. Browsers implement careful policies for + # XmlHttpRequest: + # + # * Normally, only same-domain requests are allowed. + # + # * Some browsers (e.g. Firefox 3.5 and later) relax this + # carefully: + # + # * if it is a 'simple' GET or POST request (which can + # include no custom headers), it is allowed to be cross + # domain. These requests will not be recognized as AJAX. + # + # * if a 'preflight' check with the server confirms that the + # server is expecting and allows the request, cross domain + # requests even with custom headers are allowed. These + # requests will be recognized as AJAX, but can only get + # through when the developer has specifically opted in to + # allowing the cross-domain POST request. + # + # So in all cases, it is safe to allow these requests through. + return self._accept(request) + + if request.is_secure(): + # Strict referer checking for HTTPS + referer = request.META.get('HTTP_REFERER') + if referer is None: + return self._reject(request, REASON_NO_REFERER) + + # The following check ensures that the referer is HTTPS, + # the domains match and the ports match. This might be too strict. + good_referer = 'https://%s/' % request.get_host() + if not referer.startswith(good_referer): + return self._reject(request, REASON_BAD_REFERER % + (referer, good_referer)) + + # If the user didn't already have a CSRF cookie, then fall back to + # the Django 1.1 method (hash of session ID), so a request is not + # rejected if the form was sent to the user before upgrading to the + # Django 1.2 method (session independent nonce) + if cookie_is_new: + try: + session_id = request.COOKIES[settings.SESSION_COOKIE_NAME] + csrf_token = _make_legacy_session_token(session_id) + except KeyError: + # No CSRF cookie and no session 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_COOKIE) + else: + csrf_token = request.META["CSRF_COOKIE"] + + # check incoming token + request_csrf_token = request.POST.get('csrfmiddlewaretoken', None) + if request_csrf_token != csrf_token: + if cookie_is_new: + # probably a problem setting the CSRF cookie + return self._reject(request, REASON_NO_CSRF_COOKIE) + else: + 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) + # Content varies with the CSRF cookie, so set the Vary header. + patch_vary_headers(response, ('Cookie',)) + response.csrf_processing_done = True + return response + + +class CsrfResponseMiddleware(object): + """ + DEPRECATED + Middleware that post-processes a response to add a csrfmiddlewaretoken. + + This exists for backwards compatibility and as an interim measure until + applications are converted to using use the csrf_token template tag + instead. It will be removed in Django 1.4. + """ + def __init__(self): + import warnings + warnings.warn( + "CsrfResponseMiddleware and CsrfMiddleware are deprecated; use CsrfViewMiddleware and the template tag instead (see CSRF documentation).", + PendingDeprecationWarning + ) + + def process_response(self, request, response): + if getattr(response, 'csrf_exempt', False): + return response + + if response['Content-Type'].split(';')[0] in _HTML_TYPES: + csrf_token = get_token(request) + # If csrf_token is None, we have no token for this request, which probably + # means that this is a response from a request middleware. + if csrf_token is None: + return response + + # ensure we don't add the 'id' attribute twice (HTML validity) + idattributes = itertools.chain(("id='csrfmiddlewaretoken'",), + itertools.repeat('')) + def add_csrf_field(match): + """Returns the matched <form> tag plus the added <input> element""" + return mark_safe(match.group() + "<div style='display:none;'>" + \ + "<input type='hidden' " + idattributes.next() + \ + " name='csrfmiddlewaretoken' value='" + csrf_token + \ + "' /></div>") + + # Modify any POST forms + response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content) + if n > 0: + # Content varies with the CSRF cookie, so set the Vary header. + patch_vary_headers(response, ('Cookie',)) + + # Since the content has been modified, any Etag will now be + # incorrect. We could recalculate, but only if we assume that + # the Etag was set by CommonMiddleware. The safest thing is just + # to delete. See bug #9163 + del response['ETag'] + return response + + +class CsrfMiddleware(object): + """ + Django middleware that adds protection against Cross Site + Request Forgeries by adding hidden form fields to POST forms and + checking requests for the correct value. + + CsrfMiddleware uses two middleware, CsrfViewMiddleware and + CsrfResponseMiddleware, which can be used independently. It is recommended + to use only CsrfViewMiddleware and use the csrf_token template tag in + templates for inserting the token. + """ + # We can't just inherit from CsrfViewMiddleware and CsrfResponseMiddleware + # because both have process_response methods. + def __init__(self): + self.response_middleware = CsrfResponseMiddleware() + self.view_middleware = CsrfViewMiddleware() + + def process_response(self, request, resp): + # We must do the response post-processing first, because that calls + # get_token(), which triggers a flag saying that the CSRF cookie needs + # to be sent (done in CsrfViewMiddleware.process_response) + resp2 = self.response_middleware.process_response(request, resp) + return self.view_middleware.process_response(request, resp2) + + def process_view(self, request, callback, callback_args, callback_kwargs): + return self.view_middleware.process_view(request, callback, callback_args, + callback_kwargs) diff --git a/parts/django/django/middleware/doc.py b/parts/django/django/middleware/doc.py new file mode 100644 index 0000000..4f91503 --- /dev/null +++ b/parts/django/django/middleware/doc.py @@ -0,0 +1,19 @@ +from django.conf import settings +from django import http + +class XViewMiddleware(object): + """ + Adds an X-View header to internal HEAD requests -- used by the documentation system. + """ + def process_view(self, request, view_func, view_args, view_kwargs): + """ + If the request method is HEAD and either the IP is internal or the + user is a logged-in staff member, quickly return with an x-header + indicating the view function. This is used by the documentation module + to lookup the view function for an arbitrary page. + """ + if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or + (request.user.is_active and request.user.is_staff)): + response = http.HttpResponse() + response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__) + return response diff --git a/parts/django/django/middleware/gzip.py b/parts/django/django/middleware/gzip.py new file mode 100644 index 0000000..47f75aa --- /dev/null +++ b/parts/django/django/middleware/gzip.py @@ -0,0 +1,38 @@ +import re + +from django.utils.text import 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 compressing non-OK or really short responses. + if response.status_code != 200 or 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 respones 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 + + response.content = compress_string(response.content) + response['Content-Encoding'] = 'gzip' + response['Content-Length'] = str(len(response.content)) + return response diff --git a/parts/django/django/middleware/http.py b/parts/django/django/middleware/http.py new file mode 100644 index 0000000..75af664 --- /dev/null +++ b/parts/django/django/middleware/http.py @@ -0,0 +1,51 @@ +from django.core.exceptions import MiddlewareNotUsed +from django.utils.http import http_date + +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.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', None) + 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', None) + if if_modified_since == response['Last-Modified']: + # Setting the status code is enough here (same reasons as + # above). + response.status_code = 304 + + return response + +class SetRemoteAddrFromForwardedFor(object): + """ + This middleware has been removed; see the Django 1.1 release notes for + details. + + It previously set REMOTE_ADDR based on HTTP_X_FORWARDED_FOR. However, after + investiagtion, it turns out this is impossible to do in a general manner: + different proxies treat the X-Forwarded-For header differently. Thus, a + built-in middleware can lead to application-level security problems, and so + this was removed in Django 1.1 + + """ + def __init__(self): + import warnings + warnings.warn("SetRemoteAddrFromForwardedFor has been removed. " + "See the Django 1.1 release notes for details.", + category=DeprecationWarning) + raise MiddlewareNotUsed()
\ No newline at end of file diff --git a/parts/django/django/middleware/locale.py b/parts/django/django/middleware/locale.py new file mode 100644 index 0000000..b5e4949 --- /dev/null +++ b/parts/django/django/middleware/locale.py @@ -0,0 +1,25 @@ +"this is the locale selecting middleware that will look at accept headers" + +from django.utils.cache import patch_vary_headers +from django.utils import translation + +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 process_request(self, request): + language = translation.get_language_from_request(request) + translation.activate(language) + request.LANGUAGE_CODE = translation.get_language() + + def process_response(self, request, response): + patch_vary_headers(response, ('Accept-Language',)) + if 'Content-Language' not in response: + response['Content-Language'] = translation.get_language() + translation.deactivate() + return response diff --git a/parts/django/django/middleware/transaction.py b/parts/django/django/middleware/transaction.py new file mode 100644 index 0000000..96b1538 --- /dev/null +++ b/parts/django/django/middleware/transaction.py @@ -0,0 +1,27 @@ +from django.db import 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 process_request(self, request): + """Enters transaction management""" + transaction.enter_transaction_management() + transaction.managed(True) + + def process_exception(self, request, exception): + """Rolls back the database and leaves transaction management""" + if transaction.is_dirty(): + transaction.rollback() + transaction.leave_transaction_management() + + def process_response(self, request, response): + """Commits and leaves transaction management.""" + if transaction.is_managed(): + if transaction.is_dirty(): + transaction.commit() + transaction.leave_transaction_management() + return response |