Django: regular middleware called twice

I have special middleware that is called twice for each request, and I don’t understand why. This is my middleware:

class MyMiddleWare(object): def process_request(self, request): print 'FOO' return None 

This is my middleware setup:

 MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'MyMiddleware', ) 

And this is the result in the console after a request to the home page:

 [28/Jun/2013 19:48:26] FOO [28/Jun/2013 19:48:26] "GET / HTTP/1.1" 200 7468 [28/Jun/2013 19:48:27] FOO 

I tried to comment on all the other average problems, and the problem is the same. What should I do?

ps: the described behavior is reproduced in each view

UPDATE

I tried to implement process_view , not process_request , and it is called once, as expected ... why?

UPDATE 2 :

process_response is called twice as process_request

UDATE 3 :

ooooh shiiiit! This is a request to favicon.ico (which I have not yet defined) ... which calls this file?

+4
source share
2 answers

The problem is that if you use favicon.ico, defining it as the django url (like the code below):

 (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': settings.MEDIA_URL+'images/favicon.ico'}), 

All your middleware is called twice: 1 time for the requested page + 1 time for the icon (which is always called by the browser). The solution is simple: don't use django urls to serve your vaficon, instead put something like:

 <link rel="icon" type="image/png" href="{% static 'core/img/favicon.ico' %}" /> 

in the <head> your base template!

+7
source

The best solution is to add a condition to your middlevare function, which filters all the service functions.

 if view_func.__name__ != 'serve': 
+1
source

Source: https://habr.com/ru/post/1488759/


All Articles