Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: custom middleware called twice

I have a custom middleware which is called twice for every 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 setting:

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 output in the console after homepage request:

[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 out all the other middlewares and the problem is the same. What should I do?

ps: the described behavior is replicable in each view

UPDATE:

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

UPDATE 2:

process_response is called twice like process_request

UDATE 3:

ooooh shiiiit! It's a request to favicon.ico (which I haven't defined myself)... who is calling this file?

like image 422
daveoncode Avatar asked Jun 28 '13 20:06

daveoncode


2 Answers

The problem is that if you serve favicon.ico by defining it as 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 get called twice: 1 time for the page you have requested + 1 time for the favicon (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> of your base template!

like image 88
daveoncode Avatar answered Sep 19 '22 12:09

daveoncode


Better solution is to add condition into your middlevare function that filters all serve functions.

if view_func.__name__ != 'serve':
like image 44
Honza Kremeň Avatar answered Sep 20 '22 12:09

Honza Kremeň