【问题标题】:Implementing State Machine for e-Commerce (Django)为电子商务实现状态机(Django)
【发布时间】:2017-02-16 05:47:33
【问题描述】:

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

此外,购物车使用 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,而不是作为一个单独的对象。

不胜感激任何建议!

【问题讨论】:

  • django-fsm 可能是你需要的
  • @Nghung 我看了一下。似乎它适用于模型,如果我在会话中存储状态和购物车信息,我将不会使用模型..fsm 仍然相关吗?也许我错过了什么
  • 对不起,我错过了您正在使用会话。请查看transitions 包。当一个对象离开或进入一个状态时,可以附加一个callback来改变会话状态。
  • @Nghung 太好了,谢谢!这看起来像是我可以肯定使用的东西。谢谢 :) 你想发布一个答案以便我标记它吗?

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


【解决方案1】:

如前所述,名为transitions 的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!'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多