2017-02-16 11 views
0

私は電子商取引プロジェクトのためのステートマシンを実装することを考えています - 特に、空のカートから支払いが行われる状態へのワークフロー。電子商取引用ステートマシンを実装する(Django)

さらに、カートは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 
    }, 
    ... 
} 

私がやっていることが重複しているかどうかは分かりません。おそらくCart(別の属性)内に状態を実装し、別のオブジェクトとして実装するべきではないでしょうか。

アドバイスありがとうございます。

+0

[ジャンゴ-FSM](https://github.com/kmmbvnr/django-fsm)あなたは、私はそれを見ていた – Nghung

+0

@Nghungを必要とするものもあります。それはモデルのためのものだと思う、もし私がセッションで州とカートの情報を保存しているなら、私はモデルを使用しないだろう。たぶん私は何かを逃した –

+1

申し訳ありません私はあなたがセッションを使用していることを逃した。 [移行](https://github.com/tyarkoni/transitions)パッケージをご覧ください。オブジェクトが状態を離れるか状態に入るとき、セッション状態を変更する[コールバック](https://github.com/tyarkoni/transitions#callbacks)を添付することができます。 – Nghung

答えて

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!' 
関連する問題