简体   繁体   中英

Django app ERR_EMPTY_RESPONSE when adding custom middleware to settings.py

I've created a LoggedInUserMiddleware in my project/app/middleware.py file and added it as the last entry in the MIDDLEWARE portion of my project/master/settings.py file. Before adding it to settings.py the app responds just fine. After adding it to settings.py i get an ERR_EMPTY_RESPONSE from any url of my app.

My LoggedInUserMiddleware currently looks like this just to try to get it to not crash things.

class LoggedInUserMiddleware(object):
    def process_request(self, request):
        return None

As I understand it, that middleware should execute with every single new html request, but do absolutely nothing.

You have written an old-style middleware (Django < 1.10). If you are using the MIDDLEWARE setting instead of MIDDLEWARE_CLASSES , then you should write a new-style middleware .

One option is to use the MiddlewareMixin .

from django.utils.deprecation import MiddlewareMixin

class LoggedInUserMiddleware(MiddlewareMixin):
    def process_request(self, request):
        return None

However, if you do not need to support the old MIDDLEWARE_CLASSES setting, there is no need to use the mixin, and I would start from the example in the docs:

class LoggedInUserMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM