【问题标题】:django global variabledjango 全局变量
【发布时间】:2012-09-30 11:06:15
【问题描述】:

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

def other 不返回 6,但应该是 6 对吧?如何在我的视图中全局访问变量?

【问题讨论】:

  • 在你想在全局范围内使用num的所有函数中添加global num
  • 您可以按照答案中的说明进行操作,也可以将变量数据添加到数据库中并在全局范围内使用该数据。

标签: python django django-views


【解决方案1】:

使用sessions。这正是它们的设计目的。

def foo(request):
   num = request.session.get('num')
   if num is None:
      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

如果会话已过期,或者会话中不存在num(未设置),则request.session.get('num') 将返回None。如果你想给num 一个默认值,那么你可以这样做request.session.get('num',5) - 现在如果num 没有在会话中设置,它将默认为5。当然,当你这样做时,你不需要if num is None 检查。

【讨论】:

  • 很好的答案,会话可能是他需要的。你可以只做num = request.session.get('num', 1) 并删除接下来的两行。
  • 但是会话可以从客户端清除吧?!
  • + 需要 JSON 序列化 (TypeError: Object of type 'XyGlobals' is not JSON serializable)
【解决方案2】:

您可以在其中一个函数之外声明 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)

如果你给一个变量赋值,你只需要使用 global 关键字,这就是为什么你不需要在第二个函数中使用global GLOBAL_Entry

【讨论】:

  • 这适用于 int 值,如果我在函数中有查询并且想全局使用它怎么办。例如'GLOBAL_Entry=Entry.objects.filter(id = 3)' 如何声明'GLOBAL_Entry'
  • 错误提示未定义名称“null”,您确定 null 部分吗?
  • 糟糕,我的意思是None。语言错误。
  • 当 Django 从多线程 uwsgi 执行时它会起作用吗?例如,start 将从一个线程调用,other 从另一个线程调用
【解决方案3】:

您可以打开 settings.py 并添加您的变量和值。 在您的源代码中,只需添加这些行

from django.conf import settings
print settings.mysetting_here

现在您可以为所有项目全局访问您的变量。 试试这个,它对我有用。

【讨论】:

  • 设置仅适用于 simple 类型(如字符串、int) - JSON 不起作用
【解决方案4】:

您也可以在 other() 方法中使用 global 关键字,如下所示:

def other(request):
   global num
   num = num+1
   return HttpResponse("num= %d" %num)

现在它会返回6。这意味着你想在哪里使用全局变量,你应该使用global关键字来使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多