Created
June 10, 2013 22:35
-
-
Save davedash/5753035 to your computer and use it in GitHub Desktop.
Middleware that appends slashes as to not break our url routes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from logger import statsd | |
| import settings | |
| class CanonicalMiddleware(object): | |
| """Adjust incoming URLs to have a / so our routing still works. | |
| Additionally this saves the canonical version of the url at | |
| `request.canonical`. | |
| """ | |
| def process_request(self, request): | |
| if not request.path.endswith('/'): | |
| statsd.sc.increment("web.middleware.canonical.canonize_path") | |
| request.path += "/" | |
| if not request.path_info.endswith('/'): | |
| request.path_info += "/" | |
| if not request.META['PATH_INFO'].endswith('/'): | |
| request.META['PATH_INFO'] += '/' | |
| proto = 'http' | |
| if request.is_secure(): | |
| proto = 'https' | |
| host = request.META.get('HTTP_HOST', settings.MAIN_DOMAIN) | |
| request.canonical = u'{}://{}{}'.format(proto, host, request.path) | |
| if request.META.get('QUERY_STRING'): | |
| request.canonical += u'?{}'.format(request.META['QUERY_STRING']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment