访问脚本主模块中定义的python类变量 [英] Accessing python class variable defined inside the main module of a script

查看:122
本文介绍了访问脚本主模块中定义的python类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django项目,使用芹菜进行异步处理。我正在使用python 2.7。



我的django项目中有一个模块 client.py 中的类: / p>

 #client.py 
class客户端:
def __init __(self):
#code用于打开持久连接并将连接客户端保存在类变量
...
self.client =< connection client>

def get_connection_client(self):
return self.client

def send_message(self,message):
#---不是确切的代码但是这是我需要访问的功能,我需要访问客户端变量---
self.client.send(message)
#使用上述方法发送消息的其他功能
...

此类只需要实例化一次即可创建一个持久性连接到远程服务器



我运行无限期运行的脚本 connection.py / p>

 #connection.py 
从客户端导入客户端
如果__name__ =='__main__':
clientobj = Client()
client = clientobj.get_connection_client()
#阻止进程
while True:
#等待来自远程服务器的消息
..

我需要访问变量客户端从另一个模块 tasks.py (芹菜需要)。






 #tasks.py 
...
从客户端导入客户端
@app。任务
def function():
#需要访问客户端变量
#< ???如何获取
#已建立连接的客户端变量?>
message =使用已建立的连接发送到服务器的消息
client.send_message(message)

所有三个python模块都在同一台机器上。 connection.py 作为独立脚本执行,首先执行。在 tasks.py 中的方法 function()在需要时被称为项目的其他模块多次,我无法在此方法中实例化客户端类。全局变量不起作用。






在java中,我们可以创建全局静态变量并在整个项目中访问它。我们如何在python中执行此操作?



方法我可以想到但不知道是否可以在python中完成:




  • 将此变量保存在一个通用文件中,使其可以在我的项目中的其他模块中访问

  • 将此客户端作为django或芹菜中的设置保存,并访问所需模块中的此设置。

  • 根据sebastian的建议,另一种方式是在运行进程之间共享变量。我本来是想做到这一点如何在python中执行此操作?



对于那些有兴趣知道为什么需要这样做的人,请看到这个问题。它解释了完整的系统设计和所涉及的各种组件。



我可以接受需要更改代码结构的建议。

解决方案

多处理 提供了您需要的所有工具。



connection.py



来自multiprocessing.managers的

 从客户端导入BaseManager 
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()

tasks.py p>

  from multiprocessing.managers import BaseManager 
class ClientManager(BaseManager):pass
ClientManager.register('get_client' )
manager = ClientManager(a ddress =('localhost',50000),authkey ='abracadabra')
manager.connect()
client = manager.get_client()

@ app.task
def function():
message =使用建立的连接发送到服务器的消息
client.send_message(message)


I have a django project that uses celery for async task processing. I am using python 2.7.

I have a class in a module client.py in my django project:

# 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
    ...

This class needs to be instantiated only once to create one persistent connection to a remote server.

I run a script connection.py that runs indefinitely:

# 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
        ...

I need to access the variable client from another module tasks.py (needed for 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)

All the three python modules are on the same machine. The connection.py is executed as a standalone script and is executed first. The method function() in tasks.py is called multiple times across other modules of the project whenever required, thus, I can't instantiate the Client class inside this method. Global variables don't work.


In java, we can create global static variable and access it throughout the project. How do we do this in python?

Approaches I can think of but not sure if they can be done in python:

  • Save this variable in a common file such that it is accessible in other modules in my project?
  • Save this client as a setting in either django or celery and access this setting in the required module?
  • Based on suggestions by sebastian, another way is to share variables between running processes. I essentially want to do that. How do I do this in python?

For those interested to know why this is required, please see this question. It explains the complete system design and the various components involved.

I am open to suggestions that needs a change in the code structure as well.

解决方案

multiprocessing provides all the tools you need to do this.

connection.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()

tasks.py

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)

这篇关于访问脚本主模块中定义的python类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆