Is there a way to access the context from everywhere in Django?

前端 未结 3 1883
执笔经年
执笔经年 2020-12-10 05:49

I\'m looking for a way to have a global variable that is accessible by any module within my django request without having to pass it around as parameter. Traditionally in ot

3条回答
  •  一整个雨季
    2020-12-10 06:00

    It's still not completely clear to me what you're trying to achieve, but it sounds like you might want something like the following.

    If you create a piece of middleware in, say...

    myproject/myapp/middleware/globalrequestmiddleware.py
    

    ...which looks like this...

    import thread
    
    class GlobalRequestMiddleware(object):
        _threadmap = {}
    
        @classmethod
        def get_current_request(cls):
            return cls._threadmap[thread.get_ident()]
    
        def process_request(self, request):
            self._threadmap[thread.get_ident()] = request
    
        def process_exception(self, request, exception):
            try:
                del self._threadmap[thread.get_ident()]
            except KeyError:
                pass
    
        def process_response(self, request, response):
            try:
                del self._threadmap[thread.get_ident()]
            except KeyError:
                pass
            return response
    

    ...then add it into your settings.py MIDDLEWARE_CLASSES as the first item in the list...

    MIDDLEWARE_CLASSES = (
        'myproject.myapp.middleware.globalrequestmiddleware.GlobalRequestMiddleware',
        # ...
    )
    

    ...then you can use it anywhere in the request/response process like this...

    from myproject.myapp.middleware.globalrequestmiddleware import GlobalRequestMiddleware
    
    # Get the current request object for this thread
    request = GlobalRequestMiddleware.get_current_request()
    
    # Access some of its attributes
    print 'The current value of session variable "foo" is "%s"' % request.SESSION['foo']
    print 'The current user is "%s"' % request.user.username
    
    # Add something to it, which we can use later on
    request.some_new_attr = 'some_new_value'
    

    ...or whatever it is you want to do.

提交回复
热议问题