为电子商务实施状态机 (Django)

Implementing State Machine for e-Commerce (Django)

我正在考虑为电子商务项目实施状态机 - 专门用于从空购物车到付款状态的工作流程。

另外,Cart使用Django的session框架存储在session中。我不知道状态机应该是购物车实现的一部分还是独立的,而是通过 API.

'connected' 到购物车

只是一个免责声明,我对状态机真的很陌生,所以我不太熟悉理论概念,但从我自己的研究来看,它似乎对我的项目非常有用。

我的思路是这样的:

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
    },
    ...
}

我不确定我正在做的事情是否多余,也许我应该在购物车本身(作为一个属性)而不是作为一个单独的对象中实现状态。

如有任何建议,我们将不胜感激!

如前所述,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!'