python 如何在JSON中创建具有状态持久性的Streamlit Jmeter 板?

sshcrbum  于 6个月前  发布在  Python
关注(0)|答案(1)|浏览(83)

我正在做一个Streamlit Jmeter 板项目,我需要保存应用程序的状态,包括各种参数和行为,以JSON。目标是确保当用户与 Jmeter 板交互并对参数进行更改时,这些更改会自动序列化到JSON中并保存。当 Jmeter 板刷新或重新访问时,状态应该从JSON文件无缝加载
下面是Python示例I'

m currently working on:

python
Copy code
import os
import json
from typing import List

from pydantic import BaseModel, root_validator

STATE_PATH = os.path.join(os.getcwd(), 'crop_state.json')

class SelectCameraState(BaseModel):
    selected_cameras: List[str]

class CropState(BaseModel):
    crop_type: str  # Anchor / Fixed
    bbox: List[int]
    anchor_class: str
    anchor_position: List[int]

class ProcessState(BaseModel):
    feature_extractor: str
    embedding_processor: str
    outlier_detector: str

class ApplicationState(BaseModel):
    camera_select_state: SelectCameraState
    crop_state: CropState

    class Config:
        validate_assignment = True

    @root_validator
    def update_property(cls, values):
        with open(STATE_PATH, 'w') as f:
            f.write(json.dumps(values))

a = ApplicationState()
a.camera_select_state = SelectCameraState()
a.camera_select_state.selected_cameras = ["blah"]

字符串
然而,我在使用这种方法时遇到了一些问题:
当使用Pydantic模型时,对可变对象(如列表)的更改不会被根验证器自动识别,从而导致保存状态时出现问题。
这种方法与Streamlit应用程序中的常规状态管理模式不一致。
我正在寻求如何更有效和更常规地在Streamlit Jmeter 板中实现状态持久化的指导,我愿意接受设计模式、库或技术的建议,这些建议可以帮助我在Streamlit中实现状态持久化,同时适应可变对象的更改并维护干净、有组织的代码。
如果您有任何关于在Streamlit中处理状态持久性的建议、代码示例或最佳实践,我们将不胜感激。

g6ll5ycj

g6ll5ycj1#

你想要的pydantic函数是model_dump_json()(至少在较新的pydantic版本中是这样)。
一个写json文件的例子可能看起来像这样:

with open("applicationstate.json", "w") as jsonfile:
    jsonfile.write(applicationstate_model.model_dump_json(indent=2)

字符串
Streamlit已经为多页面应用程序提供了一个内置的会话状态-你也可以使用它,或者只是使用你自己的模型。无论如何,看看链接文档中关于回调的部分。基本上,你可以编写你的函数来将你的状态写入序列化,并使用on_change事件触发它:

import streamlit as st

def save_application_state():
    with open("applicationstate.json", "w") as jsonfile:
        jsonfile.write(applicationstate_model.model_dump_json(indent=2)

applicationstate_model = st.toggle('Activate feature', on_change=save_application_state)

if on:
    st.write('Feature activated!')


我还没有测试上面的代码,但它至少应该让你开始。

相关问题