I made my own Django Middleware so that I can access request information from anywhere

I started thinking about whether the login user could be stored in the model user_created (creator) and user_updated (updater) by common processing.

Until then, I wrote the process of passing user information from view to form and storing it in user_created and user_updated.

What is Django's middleware?

From Official

Middleware is a framework for adding hooks to Django's request / response processing.

You can define the processing to be performed when sending a request or before returning a response.

Implementation of middleware

Define a function that operates threadlocal

common/middlewares/threadlocals.py


from threading import local


THREAD_LOCAL = local()


def set_thread_variable(key, value):
    """Store values in thread-local data
    """
    setattr(THREAD_LOCAL, key, value)


def get_thread_variable(key, default=None):
    """Get values from thread-local data
    """
    return getattr(THREAD_LOCAL, key, default)


def get_request():
    """Get request information from thread local data
    """
    return get_thread_variable('request')

Define middleware class

common/middlewares/request_store_middleware.py


from common.middlewares.threadlocals import set_thread_variable
from django.utils.deprecation import MiddlewareMixin


class RequestStoreMiddleware(MiddlewareMixin):
    def process_request(self, reuqest):
        set_thread_variable('request', reuqest)

Since we want request information this time, we will define only process_request.

Added to MIDDLEWARE in settings.py

settings.py


.
..
...
MIDDLEWARE = [
    .
    ..
    ...
    'common.middlewares.request_store_middleware.RequestStoreMiddleware', #add to
]
...
..
.

Just call get_request wherever you like

I decided to use it in models.py because the purpose is to store user information when saving to DB.

common/models.py


.
..
...
from common.middlewares.threadlocals import get_request
from django.db.models.signals import pre_save
...
..
.
class Company(BaseModel):
    """Corporate model class
    """
    ...
    ..
    .
    created_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)
    updated_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)
...
..
.
def set_user_receiver(sender, instance, *args, **kwargs)
    request = get_request() #Authentication check may be done before storing user information
    instance.created_user = request.user
    instance.updated_user = request.user


pre_save.connect(set_user_receiver, sender=Company) # pre_If you use save, save()You can register the function you want to call before execution.

end

Recommended Posts

I made my own Django Middleware so that I can access request information from anywhere
[Python] I made my own library that can be imported dynamically
I tried to publish my own module so that I can pip install it
I made my own language. (1)
I made my own language (2)
I made my own AML
I made my own Python library
[Python] I made a utility that can access dict type like a path
I made a simple timer that can be started from the terminal
I made CORS custom middleware with Django
I made an AI that predicts from trivia and made me infer my trivia. Hee-AI
I made a Docker image that can call FBX SDK Python from Node.js
In Python, I made a LINE Bot that sends pollen information from location information.
I made my own parallel link robot (software version)
I made a module that can be glitched easily, but I can't pass arguments from entry_points