类定义有状态模块
pfstate的Python项目详细描述
目录
Overview
这个存储库提供pfstate–一个库/模块,它在对象/类定义(而不是在类实例中)中维护状态。模块在内部使用树C_snode数据抽象(有关C_snode的信息,请参阅其他部分)以及一些内部方法以各种方式设置/获取此内部数据。
pfstate
最简单的是,pfstate是一个在类定义中保持状态的模块(与类实例相反)。它主要是在自定义ThreadedHTTPServer类的上下文中创建的。在python中创建ThreadedHTTPServer涉及实例化ThreadedHTTPServer,并在构造函数中提供派生的BaseHTTPRequestHandler对象。这种设计模式有一些结构上的缺陷——最明显的是,从ThreadedHTTPServer级别设置内部BaseHTTPRequestHandler数据的困难。克服这个问题的一种机制是在服务器和处理程序的范围内共享一个公共的单个pfstate对象。
此外,对ThreadedHTTPServer的每次调用都会重新初始化从BaseHTTPRequestHandler派生的处理程序对象,因此该对象实例中的任何状态信息都会在调用之间丢失。
但是,通过使用pfstate模块,在handler对象中,通过保持对象中的状态而不是对象的实例,可以在调用ThreadedHTTPServer时保留状态信息。
在某些方面,这可以被认为是避免使用全局变量的更干净的方法。
有关详细信息,请参阅源代码。但是,作为一个简单的概述,建议使用此模块的方法是在字典中定义包含状态特定信息的子类,然后初始化该类。
注意,这个派生类必须检查基本对象数据的初始化,以免重新初始化已经有状态的对象,从而丢失任何其他状态信息。
frompfmisc.C_snodeimportC_snodefrompfmisc._colorsimportColorsfrompfstateimportSfromargparseimportRawTextHelpFormatterfromargparseimportArgumentParserstr_desc="some program description"str_version="1.0.0.0"parser=ArgumentParser(description=str_desc,formatter_class=RawTextHelpFormatter)parser.add_argument('--msg',action='store',dest='msg',default='',help='Message payload for internalctl control.')classD(S):""" A derived class with problem-specific state """def__init__(self,*args,**kwargs):""" Constructor """S.__init__(self,*args,**kwargs)ifnotS.b_init:d_specific= \ {'specificState':{'desc':'Additional state information','theAnswer':42,'theQuestion':'What do you get if you multiple six by nine','foundBy':'Arthur Dent'},'earthState':{'current':'Destroyed','reason':'Hyper space bypass','survivors':{'humans':['Arthur Dent','Ford Prefect','Trillian'],'dolphins':'Most of them'}}}S.d_state.update(d_specific)S.T.initFromDict(S.d_state)S.b_init=Trueiflen(S.T.cat('/this/debugToDir')):ifnotos.path.exists(S.T.cat('/this/debugToDir')):os.makedirs(S.T.cat('/this/debugToDir'))self.dp.qprint(Colors.YELLOW+"\n\t\tInternal data tree:",level=1,syslog=False)self.dp.qprint(C_snode.str_blockIndent(str(S.T),3,8),level=1,syslog=False)state=D(version=str_version,desc=str_desc,args=vars(args))iflen(args.msg):d_control=state.internalctl_process(request=json.loads(args.msg))print(json.dumps(d_control,indent=4))
Installation
安装相对简单,我们建议使用python`pip来简化模块的安装,最好是在python虚拟环境中。
Python Virtual Environment
在ubuntu上,安装python virtual environment creator
sudo apt install virtualenv
然后,为您的虚拟环境创建一个目录,例如:
mkdir ~/python-envs
您可能需要将这两行代码添加到.bashrc文件中:
exportWORKON_HOME=~/python-envs source /usr/local/bin/virtualenvwrapper.sh
请注意,根据发行版的不同,virtualenvwrapper.sh路径可能是
/usr/share/virtualenvwrapper/virtualenvwrapper.sh
随后,您可以获得.bashrc并创建一个新的python3虚拟环境:
source .bashrc mkvirtualenv --python=python3 python_env
激活或“输入”虚拟环境:
workon python_env
要停用虚拟环境:
deactivate
安装模块
pip install pfstate
Using the ^{tt1}$ docker container
为了与其他pf*包的完整性起见,提供了一个停靠的构建,尽管其实用性值得商榷,运行/构建Docker映像几乎没有什么用处。
Usage
有关pstate的用法,请参阅相关的wiki页面<;https://github.com/FNNDSC/pfstate/wiki/pfstate-overview>;`。
Command line arguments
[--msg '<JSON_formatted>'] An optional JSON formatted string exemplifying how to get and set internal variables. --msg ' { "action": "internalctl", "meta": { "var": "/", "get": "value" } }' --msg ' { "action": "internalctl", "meta": { "var": "/service/megalodon", "set": { "compute": { "addr": "10.20.1.71:5010", "baseURLpath": "api/v1/cmd/", "status": "undefined" }, "data": { "addr": "10.20.1.71:5055", "baseURLpath": "api/v1/cmd/", "status": "undefined" } } } }' [--configFileLoad <file>] Load configuration information from the JSON formatted <file>. [--configFileSave <file>] Save configuration information to the JSON formatted <file>. [-x|--desc] Provide an overview help page. [-y|--synopsis] Provide a synopsis help summary. [--version] Print internal version number and exit. [--debugToDir <dir>] A directory to contain various debugging output -- these are typically JSON object strings capturing internal state. If empty string (default) then no debugging outputs are captured/generated. If specified, then ``pfcon`` will check for dir existence and attempt to create if needed. [-v|--verbosity <level>] Set the verbosity level. "0" typically means no/minimal output. Allows for more fine tuned output control as opposed to '--quiet' that effectively silences everything.
示例
pfstate \\ --msg ' { "action": "internalctl", "meta": { "var": "/", "get": "value" } }'