实现电子商务的状态机(Django)

时间:2017-02-16 05:47:34

标签: python django session e-commerce state-machine

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

此外,Cart使用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
    },
    ...
}

我不确定我所做的事情是多余的,也许我应该在购物车内部(作为属性)实现状态而不是作为单独的对象。

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

如上所述,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!'
相关问题