2
0
mirror of https://expo.survex.com/repositories/troggle/.git synced 2025-12-17 13:57:06 +00:00

making flat files delivery more robust

This commit is contained in:
Philip Sargent
2021-03-31 17:57:43 +01:00
parent 3452c2c5d4
commit a6ed0a964e
4 changed files with 119 additions and 93 deletions

View File

@@ -1,7 +1,6 @@
from django.conf import settings
from django import http
from django.urls import reverse, resolve
#from django.core.urlresolvers import resolve
from django.urls import reverse, resolve,Resolver404
"""Non-standard django middleware is loaded from this file.
"""
@@ -17,19 +16,31 @@ class SmartAppendSlashMiddleware(object):
"""
def process_request(self, request):
"""
Rewrite the URL based on settings.SMART_APPEND_SLASH
"""
'''Called for every url so return as quickly as possible
Append a slash if SMART_APPEND_SLASH is set, the resulting URL resolves and it doesn't without the /
'''
if not settings.SMART_APPEND_SLASH:
return None
if request.path.endswith('/'):
return None
if request.path.endswith('_edit'):
return None
# Check for a redirect based on settings.SMART_APPEND_SLASH
host = http.HttpRequest.get_host(request)
old_url = [host, request.path]
new_url = old_url[:]
# Append a slash if SMART_APPEND_SLASH is set and the resulting URL
# resolves.
if settings.SMART_APPEND_SLASH and (not old_url[1].endswith('/')) and not _resolves(old_url[1]) and _resolves(old_url[1] + '/'):
new_url[1] = new_url[1] + '/'
if _resolves(old_url[1]):
return None
# So: it does not resolve according to our criteria, i.e. _edit doesn't count
new_url = old_url[:]
new_url[1] = new_url[1] + '/'
if not _resolves(new_url[1]):
return None
else:
if settings.DEBUG and request.method == 'POST':
# replace this exception with a redirect to an error page
raise RuntimeError("You called this URL via POST, but the URL doesn't end in a slash and you have SMART_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 SMART_APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1]))
if new_url != old_url:
# Redirect
@@ -45,9 +56,12 @@ class SmartAppendSlashMiddleware(object):
def _resolves(url):
try:
resolve(url)
# If the URL does not resolve, the function raises a Resolver404 exception (a subclass of Http404)
match = resolve(url)
# this will ALWAYS be resolved by expopages because it will produce pagenotfound if not the thing asked for
# so handle this in expopages, not in middleware
return True
except http.Http404:
except Resolver404:
return False
except:
print(url)