Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

django add middleware

### 1- create a middleware folder in your app ###
yourproject/yourapp/middleware
### 2- create a python file containing the middleware class ###
class CustomMiddleware(object):
    def __init__(self, get_response):
        """
        One-time configuration and initialisation.
        """
        self.get_response = get_response

    def __call__(self, request):
        """
        Code to be executed for each request before the view (and later
        middleware) are called.
        """
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        """
        Called just before Django calls the view.
        """
        return None

    def process_exception(self, request, exception):
        """
        Called when a view raises an exception.
        """
        return None

    def process_template_response(self, request, response):
        """
        Called just after the view has finished executing.
        """
        return response

### 3- Add the middleware in settings.py file ###
MIDDLEWARE = ( #  Before Django 1.10 the setting name was 'MIDDLEWARE_CLASSES'
    ... other middlewares ...,
     'yourapp.middleware.middlewareFile.MiddlewareFunction'
)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #django #add #middleware
ADD COMMENT
Topic
Name
8+2 =