--- title: Stateful Plugins keywords: fastai sidebar: home_sidebar nb_path: "nbs/plugin.stateful.ipynb" ---
{% raw %}
{% endraw %} {% raw %}
{% endraw %}

If a plugin with states are going to be used, this includes the plugins with user interaction, then StatefulPlugin should be used.

{% raw %}
{% endraw %} {% raw %}

class PersistentState[source]

PersistentState(pluginId=None, lastState=None, account=None, view=None, **kwargs) :: Item

Persistent state variables saved for plugin such as views, accounts, the last state to resume from etc.

{% endraw %} {% raw %}
{% endraw %} {% raw %}

class StatefulPlugin[source]

StatefulPlugin(runId, pluginState=None, **kwargs) :: PluginBase

Provides state/view setter and getter functions to plugin runtime

{% endraw %} {% raw %}
{% endraw %}

Setting and communicating states through PluginRun

An example stateful plugin is below.

{% raw %}
class MyStatefulPlugin(StatefulPlugin):
    
    def __init__(self, runId=None, **kwargs):
        super().__init__(runId=runId, **kwargs)

    def run(self):
        print("Running plugin")
        pass
    
    def add_to_schema(self):
        print("Adding schema")
        pass
{% endraw %}

Through this inherited class you can set states to control the flow and views that are displayed to user.

{% raw %}
from pymemri.pod.client import PodClient
from pymemri.data.schema import CVUStoredDefinition
from pymemri.plugin.pluginbase import PluginRun, register_base_schemas

# prepare
client = PodClient()
register_base_schemas(client)

# create a run
run = PluginRun(containerImage="stateful_plugin", pluginModule="StatefulPlugin", pluginName="stateful_plugin")
client.create(run)

# test the run states    
stateful = MyStatefulPlugin(runId=run.id)
stateful.started(client)
assert stateful._get_run_state(client) == RUN_STARTED

# test run views
view = CVUStoredDefinition(name="test-view")
client.create(view)
assert stateful._set_run_view(client, "non-existent-view") == False
assert stateful._set_run_view(client, "test-view") == True
assert stateful._get_run_view(client, run).name == 'test-view'
{% endraw %}