Error with django middleware

2019-08-09 22:57发布

问题:

I am trying to select database dynamically with help of a middleware(which sets a variable in threading.local) and a dbrouter(which sets the database depending upon the variable set in threading.local).

The code goes on like this:

import re
import threading 
request_cfg = threading.local()

class RouterMiddleware(object):
    def process_view( self, request, view_func, view_args, view_kwargs ):
        pattern = re.compile("\\b(http://|https://|www.|.com|8000|:|//)\\W\\d+", re.I)
        words = request.get_host()        
        db_name = [pattern.sub("", words)][0].split('.')[0]
        request_cfg.cfg = db_name
        return None

    def process_response( self, request, response ):
        if hasattr( request_cfg, 'cfg' ):
            del request_cfg.cfg
        return response


class DatabaseRouter (object):
    def _default_db( self ):
        if hasattr( request_cfg, 'cfg' ):
            return request_cfg.cfg
        else:
            return 'default'

    def db_for_read( self, model, **hints ):
        return self._default_db()

    def db_for_write( self, model, **hints ):
        return self._default_db()

My List of middleware_classes goes like this:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'subdomains.middleware.SubdomainURLRoutingMiddleware', 
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'oscar.apps.basket.middleware.BasketMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'catalogue.middleware.RouterMiddleware',
)

But there is something wrong with the middleware.Like even after doing login(request, user), the user is not set in request, i.e user is still anonymous one.

Removing the middleware solves my problem i.e user gets set in request.

Hopefully there is something wrong with middleware, but i cant figure out what! please tell me whats wrong about this code.Thanks.

回答1:

just use post_request, more explicitly, remove

def process_view( self, request, view_func, view_args, view_kwargs ):
##

with

def process_request(self, request):
##

that will do.