Python Django 全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12811523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django global variable
提问by John Smith
In views.py
在views.py中
When I try this one to access a global variable from other def:
当我尝试从其他访问全局变量时def:
def start(request):
global num
num=5
return HttpResponse("num= %d" %num) # returns 5 no problem....
def other(request):
num=num+1
return HttpResponse("num= %d" %num)
def otherdoes not return 6, but it should be 6 right ? How can I access a variable globally in my view ?
def other不返回 6,但应该是 6,对吗?如何在我的视图中全局访问变量?
采纳答案by Burhan Khalid
Use sessions. This is exactly what they are designed for.
使用会话。这正是它们的设计目的。
def foo(request):
num = request.session.get('num')
if not num:
num = 1
request.session['num'] = num
return render(request,'foo.html')
def anotherfoo(request):
num = request.session.get('num')
# and so on, and so on
If the session has expired, or numdid not exist in the session (was not set) then request.session.get('num')will return None. If you want to give numa default value, then you can do this request.session.get('num',5)- now if numwasn't set in the session, it will default to 5. Of course when you do that, you don't need the if not numcheck.
如果会话已过期,或会话中num不存在(未设置),request.session.get('num')则将返回None. 如果你想给num一个默认值,那么你可以这样做request.session.get('num',5)- 现在如果num没有在会话中设置,它将默认为5. 当然,当你这样做时,你不需要if not num支票。
回答by Nathan Villaescusa
You could declare num outside one of the functions.
您可以在其中一个函数之外声明 num 。
num = 0
GLOBAL_Entry = None
def start(request):
global num, GLOBAL_Entry
num = 5
GLOBAL_Entry = Entry.objects.filter(id = 3)
return HttpResponse("num= %d" %num) # returns 5 no problem....
def other(request):
global num
num = num + 1
// do something with GLOBAL_Entry
return HttpResponse("num= %d" %num)
You only need to use the global keyword if you are assigning to a variable, which is why you don't need global GLOBAL_Entryin the second function.
如果要分配给变量,则只需要使用 global 关键字,这就是为什么global GLOBAL_Entry在第二个函数中不需要的原因。
回答by Ashok Joshi
You can also do this by using globalkeyword in other()method like this:
您也可以通过在other()方法中使用global关键字来做到这一点,如下所示:
def other(request):
global num
num = num+1
return HttpResponse("num= %d" %num)
now It will return 6. It means wherever you want to use global variable, you should use globalkeyword to use that.
现在它将返回 6。这意味着无论您想在何处使用全局变量,都应该使用global关键字来使用它。
回答by Vinh Trieu
You can open settings.py and add your variable and value. In your source code, just add these line
您可以打开 settings.py 并添加您的变量和值。在您的源代码中,只需添加这些行
from django.conf import settings
print settings.mysetting_here
Now you can access your variable globally for all project. Try this, it works for me.
现在您可以为所有项目全局访问您的变量。试试这个,它对我有用。

