[英]Implementing State Machine for e-Commerce (Django)
我正在考虑为电子商务项目实现状态机-专门用于从空购物车到付款状态的工作流。
另外,购物车使用Django的会话框架存储在会话中。 我无法确定状态机应该是Cart实现的一部分还是独立的,而是通过API“连接”到Cart的。
只是免责声明,我真的是State Machines的新手,所以我对理论概念不太熟悉,但是从我自己的研究看来,这似乎对我的项目确实有用。
我的思考过程是这样的:
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(作为属性),而不是作为单独的对象实现。
将不胜感激任何建议!
正如讨论的那样,Python中名为状态转换的状态机实现适合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!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.