Joh*_*ith 14 python django django-views
在views.py中
当我尝试从其他人访问全局变量时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)
Run Code Online (Sandbox Code Playgroud)
def other
不回6,但它应该是6对吗?如何在视图中全局访问变量?
Bur*_*lid 17
使用会话.这正是它们的设计目标.
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
Run Code Online (Sandbox Code Playgroud)
如果会话已过期,或者num
在会话中不存在(未设置),request.session.get('num')
则会返回None
.如果你想给出num
一个默认值,那么你可以这样做request.session.get('num',5)
- 现在如果num
没有在会话中设置,它将默认为5
.当然,当你这样做时,你不需要if not num
检查.
你可以在其中一个函数之外声明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)
Run Code Online (Sandbox Code Playgroud)
如果要分配给变量,则只需要使用global关键字,这就是global GLOBAL_Entry
第二个函数中不需要的原因.