我正在考虑为一个eCommerce项目实现一个状态机--特别是从一个空购物车到付款状态的工作流程。
此外,购物车使用Django的会话框架存储在会话中。我不知道状态机应该是Cart实现的一部分还是独立的,但它是通过API连接到Cart的。
只是免责声明,我对状态机真的很陌生,所以我对理论概念不太熟悉,但从我自己的研究来看,它似乎对我的项目真的很有用。
我的想法是这样的:
state_machine.py
class StateMachine(object):
states = ['empty', 'filled', 'prepayment', 'payment_auth', 'order_placed']
... # methods that trigger state changes在cart.py中,每个操作都可能触发状态更改:
state_machine = StateMachine()
class Cart(object):
...
def add_item(self):
...
# add item to cart
# then trigger state change
state_machine.fill_cart() --> triggers a state change from 'empty' to 'filled'会话应该存储如下内容:
request.session[some_session_key] = {
'state': 'filled',
'cart': {
# cart stuff goes here
},
...
}我不确定我所做的是否是多余的,也许我应该在购物车中实现State (作为一个属性),而不是作为一个单独的对象。
如果有任何建议,将不胜感激!
发布于 2017-02-17 11:40:38
正如所讨论的,Python语言中一个名为transitions的状态机实现适合OP的需要。可以在对象进入或离开特定状态时附加回调,该回调可用于设置会话状态。
# Our old Matter class, now with a couple of new methods we
# can trigger when entering or exit states.
class Matter(object):
def say_hello(self):
print("hello, new state!")
def say_goodbye(self):
print("goodbye, old state!")
lump = Matter()
states = [
State(name='solid', on_exit=['say_goodbye']),
'liquid',
{ 'name': 'gas' }
]
machine = Machine(lump, states=states)
machine.add_transition('sublimate', 'solid', 'gas')
# Callbacks can also be added after initialization using
# the dynamically added on_enter_ and on_exit_ methods.
# Note that the initial call to add the callback is made
# on the Machine and not on the model.
machine.on_enter_gas('say_hello')
# Test out the callbacks...
machine.set_state('solid')
lump.sublimate()
>>> 'goodbye, old state!'
>>> 'hello, new state!'https://stackoverflow.com/questions/42265933
复制相似问题