[Fixed]-Implementing State Machine for e-Commerce (Django)

1๐Ÿ‘

โœ…

As discussed, a state machine implementation in Python named transitions suits the need of the OP. Callbacks can be attached when an object enters or leaves a specific state, which can be used to set session state.

# 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!'
๐Ÿ‘คNghung

Leave a comment