Search code examples
djangodjango-views

How to get 'requests' object in custom function in django


I have created one library file where I have created one function suppose :

def myfunc(param1):
    ----
    --- do something
    ----

Now If I require requests object (to get details of user or something like that), How can I get requests object without passing parameter in my function.

Note : As of now I am adding requests in my parameters (shown as below) but is there any other method as If I am calling this function to any other function I might not have requests object.

def myfunc(requests,param1):
    ----
    --- do something
    ----

Solution

  • I have get solution that I can install a middleware like TLSRequestMiddleware where we need to install :

    pip install django-tls
    

    and then,

    # settings.py
    MIDDLEWARE_CLASSES = (
        'tls.TLSRequestMiddleware',
        ...
    )
    

    In case in django version 1.10, you update package as :

    try:
        from threading import local
    except ImportError:
        from django.utils._threading_local import local
    
    _thread_locals = local()
    
    def get_current_request():
        return getattr(_thread_locals, 'request', None)
    
    def get_current_user():
        request = get_current_request()
        if request:
            return getattr(request, 'user', None)
    
    class ThreadLocalMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            _thread_locals.request = request
            return self.get_response(request)
    

    Also there is option like

    pip install django-crum
    

    and then,

    # settings.py
    MIDDLEWARE_CLASSES = (
         'crum.CurrentRequestUserMiddleware',
        ...
    )
    

    I hope this will help !