Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

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

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 other MVCs, I would store it in the request context or session and access the context with something like a "get_current_context" method (which I couldn't find in Django).

Is there something like this, or some other mechanism that will allow me to have a value available from anywhere in the request context?

TIA!

UPDATE: My research has only come up with one viable solution - thread locals (some would argue it's not viable, but there's a pretty active discussion about it, with pros and cons and seems like most people think you should be able to use it in Django, if you do it responsibly).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...