Middleware, простое, на основе flatpagesMiddleware. Используется для обработки адресов вида domain.ru/username/bla-bla, если не найдено соответствие в urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class UsernameFallbackMiddleware(object):
"""
use for process urls like (r'^(?P<username>\w+)/$', org_by_username, {}, 'org_by_username')
"""
def process_response(self, request, response):
if response.status_code != 404:
return response # No need to check for a flatpage for non-404 responses.
if not request.path_info.endswith('/') and settings.APPEND_SLASH:
return HttpResponseRedirect("%s/" % request.path)
url = re.search(r'^(?P<username>\w+)/$', request.path_info.lstrip('/'))
if url is None:
return response # wrong url
try:
return org_by_username(request, username=url.group('username'))
# Return the original response if any errors happened. Because this
# is a middleware, we can't assume the errors will be caught elsewhere.
except Http404:
return response
except:
if settings.DEBUG:
raise
return response