<commit_before>from django.http import Http404
from django.contrib.sites.models import Site
from . import tenant


# NOTE: this MUST come first in the middleware order
class CurrentTenantMiddleware(object):
    def process_request(self, request):
        try:
            tenant._set_for_request(request)
        except ValueError as e:
            raise Http404(e)
        request.urlconf = tenant._get_urls()
        request.tenant = tenant
        # TODO wonder what else is screwed up by changing _meta.db_table on the fly!!??
        Site.objects.clear_cache()
        
    def process_response(self, request, response):
        self._unset()
        return response

    def process_exception(self, request, exception):
        self._unset()

    def _unset(self):
        try:
            tenant._unset()
        except AttributeError:
            pass<commit_msg>Hacky tenant fix to prevent 500 error on rendering 404<commit_after>import logging

from django.http import Http404
from django.contrib.sites.models import Site
from . import tenant


# NOTE: this MUST come first in the middleware order
class CurrentTenantMiddleware(object):
    def process_request(self, request):
        try:
            tenant._set_for_request(request)
        except ValueError as e:
            raise Http404(e)
        request.urlconf = tenant._get_urls()
        request.tenant = tenant
        # TODO wonder what else is screwed up by changing _meta.db_table on the fly!!??
        Site.objects.clear_cache()
        
    def process_response(self, request, response):
        logging.debug('unsetting tenant in response')
        self._unset()
        return response

    # Take this out for now as it causes an error when trying to render a 404
    # def process_exception(self, request, exception):
    #     logging.debug('unsetting tenant in exception response')
    #     self._unset()

    def _unset(self):
        try:
            tenant._unset()
        except AttributeError:
            pass
{'fraction_non_alphanumeric': 0.07196401799100449, 'fraction_numerical': 0.010494752623688156, 'mean_word_length': 2.5, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3845563', 'n_tokens_mistral': 542, 'n_tokens_neox': 524, 'n_words': 175}