Python django 如何全局使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28792142/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:45:55  来源:igfitidea点击:

django how to use a variable globally

pythondjango

提问by Md. Tanvir Raihan

I have a variable in one of my view

我的一个观点中有一个变量

def ViewName(request):
      simple_variable = request.session['value']

in the same views.py file,i have another view

在同一个 views.py 文件中,我有另一个视图

def AnotherViewName(request):
    --------------------
    --------------------

now i want to use the variable simple_variablein my AnotherViewNameview ,i have tried

现在我想simple_variable在我的AnotherViewName视图中使用该变量,我已经尝试过

def AnotherViewName(request):
     global simple_variable

but,its not worked,now my question is,how can i use a variable from one view to another view in Django or how can i use a variable globally?

但是,它不起作用,现在我的问题是,如何在 Django 中使用一个视图到另一个视图的变量,或者如何全局使用变量?

in mentionthe simple_variableis storing value from the sessionand initially i have to call it within my above given ViewNameview.

在提及simple_variable是存储从值session和最初我不得不把上面给出内称之为ViewName视图。

i am using django 1.5

我正在使用 Django 1.5

采纳答案by MarshalSHI

I think you can do this way:

我认为你可以这样做:

simple_variable = initial_value 

def ViewName(request):
    global simple_variable
    simple_variable = value
    ...

def AnotherViewName(request):
    global simple_variable

回答by Mikael Svensson

There is no state shared between views as they probably runs in another thread. So if you want to share data between views you have to use a database, files, message-queues or sessions.

视图之间没有共享状态,因为它们可能在另一个线程中运行。因此,如果您想在视图之间共享数据,您必须使用数据库、文件、消息队列或会话。

Here is another stackoverflow about this. How do you pass or share variables between django views?

这是另一个关于此的stackoverflow。 如何在 Django 视图之间传递或共享变量?

Update after rego edited the question:

rego 编辑问题后更新:

Can't you do it like this?

你不能这样做吗?

def ViewName(request):
     simple_variable = request.session['value']

def AnotherViewName(request):
     simple_variable = request.session['value']

回答by jalanga

Or you can use a session.

或者您可以使用session

def ViewName(request):
      #retrieve your value
      if 'value' in request.session:
          simple_variable = request.session['value']

def AnotherViewName(request):
    #set your varaible
    request.session['value'] = simple_variable