最小状态机
fsmp的Python项目详细描述
docs | |
---|---|
tests | |
package |
最小状态机
- 免费软件:BSD许可证
Usage
importfsmclassMyTasks(fsm.FiniteStateMachineMixin):"""An example to test the state machine. Contains transitions to everywhere, nowhere and specific states. """state_machine={'created':'__all__','pending':('running',),'running':('success','failed'),'success':None,'failed':('retry',),'retry':('pending','retry'),}def__init__(self,state):"""Initialize setting a state."""self.state=statedefon_before_pending(self):print("I'm going to a pending state")
In [4]: m = MyTasks(state='created') In [5]: m.change_state('pending') I'm going to a pending state Out[5]: 'pending' In [6]: m.change_state('failed') --------------------------------------------------------------------------- InvalidTransition Traceback (most recent call last) <ipython-input-6-71d2461eee74> in <module>() ----> 1 m.change_state('failed') ~/pyfsm/src/fsm/fsm.py in change_state(self, next_state, **kwargs) 90 msg = "The transition from {0} to {1} is not valid".format(previous_state, 91 next_state) ---> 92 raise InvalidTransition(msg) 93 94 name = 'pre_{0}'.format(next_state) InvalidTransition: The transition from pending to failed is not valid
在状态转换发生之前和之后,可以包含一些钩子。
fsm将查找这些功能
pre_<state_name> post_<state_name>
给他们任何额外的参数给change_state
例如:
运行m.change_state('pending', name='john')
将触发pre_pending(name='john')
Installation
pip install fsmpy
Django integration
importfsmfromdjango.dbimportmodelsclassMyModel(models.Model,fsm.FiniteStateMachineMixin):"""An example to test the state machine. Contains transitions to everywhere, nowhere and specific states. """CHOICES=(('created','CREATED'),('pending','PENDING'),('running','RUNNING'),('success','SUCCESS'),('failed','FAILED'),('retry','RETRY'),)state_machine={'created':'__all__','pending':('running',),'running':('success','failed'),'success':None,'failed':('retry',),'retry':('pending','retry'),}state=models.CharField(max_length=30,choices=CHOICES,default='created')defon_change_state(self,previous_state,next_state,**kwargs):self.save()