Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问脚本主模块内定义的python类变量_Python_Django_Python 2.7_Celery - Fatal编程技术网

访问脚本主模块内定义的python类变量

访问脚本主模块内定义的python类变量,python,django,python-2.7,celery,Python,Django,Python 2.7,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 ... sel

我有一个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
    ...
我需要从另一个模块
tasks.py
(芹菜需要)访问变量
client


#tasks.py
...
从客户端导入客户端
@应用程序任务
def函数():
#需要访问客户端变量
# 
message=“要使用已建立的连接发送到服务器的消息”
客户端。发送消息(消息)
所有三个python模块都在同一台机器上。
connection.py
作为独立脚本执行,并首先执行。
tasks.py
中的方法
function()
会在需要时跨项目的其他模块多次调用,因此,我无法在此方法中实例化
Client
类。全局变量不起作用


在java中,我们可以创建全局静态变量并在整个项目中访问它。我们如何在python中实现这一点

我可以想到但不确定是否可以在python中实现的方法:

  • 是否将此变量保存在公共文件中,以便在我的项目的其他模块中可以访问
  • 将此客户端另存为django或芹菜中的设置,并在所需模块中访问此设置
  • 根据sebastian的建议,另一种方法是在正在运行的进程之间共享变量。我基本上想这样做。如何在python中实现这一点
对于那些有兴趣知道为什么这是必需的,请。它解释了完整的系统设计和涉及的各种组件


我也愿意接受需要更改代码结构的建议。

我没有使用django的经验,但是如果它们是从同一个脚本执行的,则可以将客户端设置为单例,或者在init.py中声明客户端,然后在需要的任何地方导入它

如果你选择单身,你可以为此做一个装饰师:

def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance
然后你会定义:

# client.py

@singleton
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
#client.py
@独生子女
类客户端:
定义初始化(自):
#用于打开持久连接并将连接客户端保存在类变量中的代码
...
self.client=
def get_连接_客户端(自身):
返回自助客户端

这就是我所能建议的,你只做了一点描述。也许可以试着更好地解释一切是如何运行的或所涉及的部分。

Python有类属性(在实例之间共享的属性)和类方法(作用于类本身的方法)。它们在类和实例上都是可读的

# client.py
class Client(object):
    _client = None

    @classmethod
    def connect(cls):
        # dont do anything if already connected
        if cls._client is None:
            return

        # code for opening a persistent connection and saving the connection client in a class variable
        ...
        cls._client = <connection client>


    @classmethod
    def get_connection_client(cls):
        return cls._client


    def __init__(self):
        # make sure we try to have a connection on initialisation
        self.connect()
#client.py
类客户端(对象):
_客户端=无
@类方法
def连接(cls):
#如果已经连接,请不要执行任何操作
如果cls.\u客户端为无:
返回
#用于打开持久连接并将连接客户端保存在类变量中的代码
...
cls.\u客户端=
@类方法
def get_连接_客户端(cls):
返回cls.\u客户端
定义初始化(自):
#确保我们尝试在初始化时建立连接
self.connect()
现在我不确定这是解决你问题的最好办法

提供了执行此操作所需的所有工具

连接.py

from multiprocessing.managers import BaseManager
from client import Client()
client = Client()
class ClientManager(BaseManager): pass
ClientManager.register('get_client', callable=lambda: client)
manager = ClientManager(address=('', 50000), authkey='abracadabra')
server = manager.get_server()
server.serve_forever()
from multiprocessing.managers import BaseManager
class ClientManager(BaseManager): pass
ClientManager.register('get_client')
manager = ClientManager(address=('localhost', 50000), authkey='abracadabra')
manager.connect()
client = manager.get_client()

@app.task
def function():
    message = "Message to send to the server using the established connection"
    client.send_message(message)
任务。py

from multiprocessing.managers import BaseManager
from client import Client()
client = Client()
class ClientManager(BaseManager): pass
ClientManager.register('get_client', callable=lambda: client)
manager = ClientManager(address=('', 50000), authkey='abracadabra')
server = manager.get_server()
server.serve_forever()
from multiprocessing.managers import BaseManager
class ClientManager(BaseManager): pass
ClientManager.register('get_client')
manager = ClientManager(address=('localhost', 50000), authkey='abracadabra')
manager.connect()
client = manager.get_client()

@app.task
def function():
    message = "Message to send to the server using the established connection"
    client.send_message(message)

如果connection.py正在导入tasks.py,则可以在tasks.py中执行此操作:

import __main__ # connection.py
main_globals = __main__.__dict__ # this "is" what you getting in connection.py when you write globals()
client = main_globals["client"]  # this client has the same id with client in connection.py
BaseManager也是一个答案,但它在本地主机上使用套接字网络,如果您还没有使用多处理,那么它不是访问变量的好方法。我的意思是,如果您需要使用多处理,您应该使用BaseManager。但是如果您不需要多处理,那么使用多处理不是一个好的选择。我的代码只是将connection.py中“client”变量的指针从 翻译


另外,如果您想使用多处理,我的代码将无法工作,因为不同进程中的解释器是不同的。

从文件中读取时使用
pickle

使用有关客户端使用情况和如何执行一切的信息更新了问题。按原样使用连接脚本,完成时将终止并释放客户端变量。。。因此,它们是独立的脚本,因此是独立的过程。假设您做了一些事情来保持客户机的活力,您需要以某种方式远程使用它(在任何其他运行的脚本中),因此我认为您需要在进程之间通信并共享这些变量。我不太清楚你为什么需要这样做,但这需要一些严肃的逻辑来在流程之间进行沟通。更新的问题。请参见编辑1和2。我的系统设计在这个问题中得到了解释-是的,我正在寻找一种在两个运行的进程之间共享变量的方法。我们如何做到这一点?必须删除“编辑”标签。请查看代码片段中的更新。谢谢。但是我需要从不同的模块访问定义的
客户机
变量。我无法使用类方法来实现这一点。请参阅问题中所做的编辑。作为旁注,函数将只能接受可以pickle的参数。这适用于大多数类型(当然也适用于所有内置类型)。