我有一个带有全局变量的 Django(所以是 Python)程序:
g_variable = []
我使用了几个函数,其中我还更改了值:
my_function()
global g_variable
g_variable.append(some_value)
在我开始多次重叠调用该程序之前效果很好 - 在 Django 中,这意味着我可以快速多次加载网页。我预计全局变量只会在每个单独的运行中是全局的,但事实并非如此。在一次运行中附加到 g_variable 的值可以在下一次运行中看到。
对我来说,这意味着我现在必须将这个变量传递给我的所有函数:
my_function(non_g_variable)
non_g_variable.append(some_value)
return non_g_variable
调用
non_g_variable = my_function(non_g_variable)
这样对吗?在我更改我的所有代码之前,我只想确保我没有遗漏任何东西。它将添加很多额外的线路和返回调用。
最佳答案
正如其他答案和评论所说,您可能应该重新设计代码以摆脱全局变量。类似的东西:
class WebpageStructure(object):
def __init__(self, html):
# parse the html
self.structure = self.parse(html)
def contains_link(self):
# figure it out using self.structure
return ...
# in the view(s)
webpage = WebpageStructure(html_to_parse)
if webpage.contains_link():
...
但是有一些选择:
如果您的代码总是在单线程中运行,您可以通过在每次运行之间将
g_variable
设置为[]
来解决此问题。可能有一个顶级函数(也许是 Django View 函数?)始终标记每次运行的开始。您应该在此顶级函数中重新初始化g_variable
。如果您的代码运行多线程,则不能使用普通的全局变量。并发线程将更新同一个全局变量。
关于 1 和 2:要在单线程中运行 Django 站点,请为开发服务器使用
manage.py runserver --nothreading
。如果您在 apache/mod_wsgi 中托管您的站点,您可以使用 daemon mode 来控制它.请注意,您可以同时运行多个单线程进程。使用全局变量将在这种情况下起作用,因为进程是隔离的。如果可能,您的代码应该适用于任何进程/线程模型。
如果您的代码运行多线程并且您真的想避免传递
g_variable
列表,您可以使用线程局部变量。文档 here和 here .
例子:
import threading
threadlocal = threading.local()
def mydjangoview(request):
# In your top-level view function, initialize the list
threadlocal.g_variable = []
# Then call the functions that use g_variable
foo()
bar()
# ... and then I guess you probably return a response?
return Response(...)
def foo():
threadlocal.g_variable.append(some_value)
def bar():
threadlocal.g_variable.append(some_other_value)
其他链接:
关于python - Django:Python 全局变量重叠,即使是单独运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10684685/