简体   繁体   中英

Get Django User ID Without Request Object Available

I extended the Django CursorDebugWrapper execute routine so on the server side I can keep track of all SQL executed. Looks like this:

class PrintQueryWrapper(django.db.backends.util.CursorDebugWrapper):
    def execute(self, sql, params=()):
        try:
            return self.cursor.execute(sql, params)
        finally:
            # record sql and do other stuff

django.db.backends.util.CursorDebugWrapper = PrintQueryWrapper

The problem is that I need each user session to do this individually, otherwise it will record all sql from all users with no concept of what came from where. If I can access the user ID from execute() I can easily keep track of the SQL from each user, but I don't know how to do that without having access to the request object.

Note: I cannot claim credit for the above code. It originated from the Django Debug Toolbar.

You can make it with middleware:

middleware.py:

import django.db.backends.util


class PrintQueryWrapper(django.db.backends.util.CursorDebugWrapper):
    user_id = None
    def execute(self, sql, params=()):
        try:
            return self.cursor.execute(sql, params)
        finally:
            print self.user_id, ": ", sql   

class PrintQueryMiddleware(object):
    def process_request(self, request): 
        PrintQueryWrapper.user_id = request.user.pk
        django.db.backends.util.CursorDebugWrapper = PrintQueryWrapper

settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'main.middleware.PrintQueryMiddleware',         # chnage path to your app
)

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