有没有办法从Django的任何地方访问上下文? [英] Is there a way to access the context from everywhere in Django?

查看:100
本文介绍了有没有办法从Django的任何地方访问上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种具有全局变量的方法,该变量可由Django请求中的任何模块访问,而不必将其作为参数传递。传统上,在其他MVC中,我会将其存储在请求上下文或会话中,并使用 get_current_context方法(在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!

更新:我的研究仅提出了一个可行的解决方案-线程本地化(有人认为这是不可行的,但是对此进行了相当积极的讨论,各有利弊大多数人认为,只要您负责任地使用它,就可以在Django中使用它。)

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).

推荐答案

目前尚不完全清楚对我来说,您想要实现的目标是,但听起来好像您可能想要以下内容。

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

...然后将其添加到您的 settings.py MIDDLEWARE_CLASSES 作为列表中的第一项...

...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.

这篇关于有没有办法从Django的任何地方访问上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆