简体   繁体   English

在Django views.py中创建变量,并在以后访问它们

[英]Create variables in Django views.py and access them at later point

Let's say I have the following two functions in views.py: 假设我在views.py中具有以下两个功能:

def foo(request):
    class_instance = SomeClass()
    return HttpResponse('whatever')

def bar(request):
    # here I want to access class_instance

Initially, foo() is called, and at a later point bar() is called, in which I want to access the variable class_instance . 最初,调用foo() ,然后再调用bar() ,在其中我要访问变量class_instance

Is there any way of accomplishing this while neither using request.session nor Django models (eg django.db.models )? 在不使用request.session或Django模型(例如django.db.models )的情况下,有什么方法可以做到这一点?

(NB: I had some luck with global variables in views.py, but this is probably a bad idea anyway and somehow didn't always work) (注意:我对views.py中的全局变量有些幸运,但是无论如何这可能不是一个好主意,而且有时也不总是有效)

You can put your variable as a module constant, especially if it's not prone to changing much. 您可以将变量作为模块常量放置,尤其是在不易改变的情况下。

CLASS_INSTANCE = SomeClass()

def foo(request):
    return HttpResponse('whatever')

def bar(request):
    # here I want to access CLASS_INSTANCE

Then both methods will have access to that, 然后这两种方法都可以访问它, but keep in mind, that functions can't change constant's value this way 但请记住,函数无法以这种方式更改常量的值 .

PS: Actually you can change the value of the global: PS:实际上,您可以更改全局值:

CLASS_INSTANCE = SomeClass()

def foo(request):
    global CLASS_INSTANCE
    CLASS_INSTANCE = SomeClass() # new instance
    return HttpResponse('whatever')

def bar(request):
    # here I want to access CLASS_INSTANCE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM