【发布时间】:2014-10-25 19:19:04
【问题描述】:
我有一个使用 celery 进行异步任务处理的 django 项目。我正在使用 python 2.7。
我的 django 项目中的模块 client.py 中有一个类:
# client.py
class Client:
def __init__(self):
# code for opening a persistent connection and saving the connection client in a class variable
...
self.client = <connection client>
def get_connection_client(self):
return self.client
def send_message(self, message):
# --- Not the exact code but this is the function I need to access to for which I need access to the client variable---
self.client.send(message)
# Other functions that use the above method to send messages
...
该类只需实例化一次即可创建到远程服务器的持久连接。
我运行了一个无限期运行的脚本connection.py:
# connection.py
from client import Client
if __name__ == '__main__':
clientobj = Client()
client = clientobj.get_connection_client()
# Blocking process
while True:
# waits for a message from the remote server
...
我需要从另一个模块 tasks.py 访问变量 client(需要 celery)。
# tasks.py
...
from client import Client
@app.task
def function():
# Need access to the client variable
# <??? How do I get an access to the client variable for the
# already established connection???>
message = "Message to send to the server using the established connection"
client.send_message(message)
所有三个 python 模块都在同一台机器上。 connection.py 作为独立脚本执行并首先执行。 tasks.py 中的方法 function() 在需要时在项目的其他模块中多次调用,因此,我无法在此方法中实例化 Client 类。全局变量不起作用。
在java中,我们可以创建全局静态变量并在整个项目中访问它。我们如何在 python 中做到这一点?
我能想到但不确定是否可以在python中完成的方法:
- 将此变量保存在一个公用文件中,以便在我的项目中的其他模块中可以访问它?
- 将此客户端保存为 django 或 celery 中的设置并在所需模块中访问此设置?
- 根据 sebastian 的建议,另一种方法是在正在运行的进程之间共享变量。我本质上想这样做。我如何在 python 中做到这一点?
如果有兴趣了解为什么需要这样做,请see this question。它解释了完整的系统设计和涉及的各种组件。
我也愿意接受需要更改代码结构的建议。
【问题讨论】:
标签: python django python-2.7 celery