You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将python-statemachine的当前状态保存并加载还原?

使用python-statemachine实现状态的持久化与还原

完全可行,python-statemachine的状态机实例支持通过序列化当前状态标识的方式,实现状态的保存与后续还原,以下是具体操作步骤:

1. 定义基础状态机

以一个订单状态机为例:

from statemachine import StateMachine, State

class OrderStateMachine(StateMachine):
    created = State('Created', initial=True)
    paid = State('Paid')
    shipped = State('Shipped')
    delivered = State('Delivered')

    pay = created.to(paid)
    ship = paid.to(shipped)
    deliver = shipped.to(delivered)

2. 保存当前状态到JSON文件

状态机的current_state属性包含当前状态对象,其name字段是可序列化的字符串,结合json模块即可完成保存:

import json

# 初始化状态机并执行状态转换
order_sm = OrderStateMachine()
order_sm.pay()  # 从created转换到paid状态

# 构造待保存的状态数据,可额外添加标识字段区分不同状态机类型
state_data = {
    "state_machine_type": "OrderStateMachine",
    "current_state": order_sm.current_state.name
}

# 写入JSON文件
with open("order_state.json", "w", encoding="utf-8") as f:
    json.dump(state_data, f, ensure_ascii=False, indent=2)

3. 从JSON文件加载并还原状态

读取JSON文件后,通过状态机的states字典(键为状态name)找到对应的State对象,直接赋值给新实例的current_state即可:

import json

# 读取保存的状态数据
with open("order_state.json", "r", encoding="utf-8") as f:
    saved_state = json.load(f)

# 初始化新的状态机实例
restored_sm = OrderStateMachine()
# 还原状态
restored_sm.current_state = restored_sm.states[saved_state["current_state"]]

# 验证还原结果
print(restored_sm.current_state.name)  # 输出: Paid

4. 扩展到数据库存储

逻辑与文件保存一致:

  • 将state_data字典序列化为JSON字符串,存入数据库的对应字段(如MySQL的TEXT、PostgreSQL的JSONB,MongoDB可直接存储字典)
  • 加载时从数据库取出JSON字符串并反序列化为字典,再按上述步骤还原状态

注意事项

  • 保存与还原时,状态机类的定义必须完全一致(状态名称、转换逻辑不能修改),否则会出现状态匹配失败的问题
  • 如果状态机绑定了业务上下文数据(如订单ID、用户信息),可将这些数据一并存入JSON或数据库,还原时注入到状态机实例
  • 对于复杂状态机,可封装专门的保存/还原工具函数,简化重复操作

内容的提问来源于stack exchange,提问作者Johan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:13:23