1

我有每天左右重新启动的 celery Python 工作进程。他们执行 Python/Django 程序。

我已经设置了某些准全局值,这些值应该在整个过程中保持在内存中。即,我有某些不经常更改的 MySQL 查询集,因此会在进程开始后立即评估一次并存储为 CONSTANT(一个不好的例子是 PROFILE = Profile.objects.get(user_id=5))。

假设我想在 celery 进程中重置这个值而不执行一个全新的程序。

该值在许多不同的模块中被导入(和使用)。我假设我必须遍历 sys.modules 中导入 CONSTANT 并删除/重置密钥的每一个?那正确吗?

这似乎很hacky。我通常使用 Memcached 之类的外部服务来协调多个进程之间的内存,但每隔一段时间,我认为本地内存比通过网络调用 NoSQL 存储更可取。

4

1 回答 1

3

It's a bit hard to say without seeing some code, but importing just sets a reference, exactly as with variable assignment: that is, if the data changes, the references change too. Naturally though this only works if it's the parent context that you've imported (otherwise assignment will change the reference, rather than updating the value.)

In other words, if you do this:

from mypackage import mymodule
do_something_with(mymodule.MY_CONSTANT)

#elsewhere
mymodule.MY_CONSTANT = 'new_value'

then all references to mymodule.MY_CONSTANT will get the new value. But if you did this:

from mypackage.mymodule import MY_CONSTANT

# elsewhere
mymodule.MY_CONSTANT = 'new_value'

the original reference won't get the new value, because you've rebound MY_CONSTANT to something else but the first reference is still pointing at the old value.

于 2012-07-13T16:18:43.357 回答