Files
postgres-web/pgweb/util/middleware.py
Magnus Hagander dcd98cf6fe Add support for automatic template based xkey
This adds an xkey header to all outgoing requests with the hash of the
name of all templates loaded. In the future we will be able to use this
to purge "all pages that included a specific template", regardless of
where in the hierarchy it was loaded.

Do this by faking a template loader that never finds anything -- but it
will record the path of the template that it tried to load, and then
leave it to another template loader to actually load it. Store this in
thread local storage (it's a bit ugly, but it's the only thing Django
supports for storing things at the request level from a template
loader), and fetch it from the middleware.
2018-06-29 18:01:35 +02:00

31 lines
1003 B
Python

from pgweb.util.templateloader import initialize_template_collection, get_all_templates
import hashlib
# Use thread local storage to pass the username down.
# http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_user():
return getattr(_thread_locals, 'user', None)
# General middleware for all middleware functionality specific to the pgweb
# project.
class PgMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
return None
def process_request(self, request):
# Thread local store for username, see comment at the top of this file
_thread_locals.user = getattr(request, 'user', None)
initialize_template_collection()
def process_response(self, request, response):
response['xkey'] = ' '.join(["pgwt_{0}".format(hashlib.md5(t).hexdigest()) for t in get_all_templates()])
return response