2017-02-16 27 views
0

我正在考慮爲電子商務項目實施狀態機 - 專門用於從空購物車到付款狀態的工作流程。爲電子商務實現狀態機(Django)

另外,Cart使用Django的會話框架存儲在會話中。我無法圍繞狀態機是否應該是購物車實施的一部分或獨立,但通過API「連接」到購物車。

只是一個免責聲明,我對狀態機非常陌生,所以我不太熟悉理論概念,但從我自己的研究來看,它似乎對我的項目非常有用。

我的思維過程是這樣的:

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

我不知道我所做的事是多餘的,也許我應該在推車本身(作爲一個屬性)內實施國家,而不是作爲單獨的對象。

希望有任何建議!

+0

[Django的FSM(https://github.com/kmmbvnr/django-fsm)可能是你所需要的 – Nghung

+0

@Nghung我在這拍了一下。它似乎是模型的意思,如果我在會話中存儲狀態和購物車信息,我將不會使用models..is fsm仍然相關?也許我錯過了什麼 –

+1

對不起,我錯過了你使用會話。請查看[transitions](https://github.com/tyarkoni/transitions)軟件包。當對象離開或進入某個狀態時,可以附加[callback](https://github.com/tyarkoni/transitions#callbacks)來更改會話狀態。 – Nghung

回答

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!'