Saving Data¶
The store lives in the bot's memory, so a restart empties it. Persistence saves the slots you mark: a marked slot is written to the database as it changes and read back into the store when the bot starts.
Keep a Value Across a Restart¶
The counter from Adding Shared State keeps each person's count in the scoped slot. With persistence set up, one line saves it:
from cascadeui import StatefulLayoutView
class CounterView(StatefulLayoutView):
instance_limit = 1
state_scope = "user"
subscribed_actions = {"SCOPED_UPDATE"}
persistent_slots = ("scoped",) # (1)!
# state_selector(), __init__(), build_ui(), and increment() as on Adding Shared State
- Marks the scoped slot to be saved. The mark is made when the class is defined and kept for good, so every later change to the slot is saved, whichever view or reducer makes it.
The counter that opens after a restart is a new panel, and its count comes from the saved slot. Every person's count is an entry in the scoped slot, so the one mark saves them all, together, as one row.
Two mistakes raise when the class is defined:
persistent_slots = ("scoped"), without the trailing comma, is a string:TypeError."scoped"listed besidescoped_slot = "settings", which sends the view's scoped writes to the"settings"slot:ValueError. Mark the slot the writes go to,persistent_slots = ("settings",).
Ways to Mark a Slot¶
| Where | The mark | Suits |
|---|---|---|
| The view class | persistent_slots = ("stats",) |
A slot a view reads |
A reducer or seed_initial_state() |
access_slot(state, "stats", key, persistent=True) |
A slot only reducers name, or a name built while the bot runs |
| The persistence setup | ApplicationPersistence(..., slots={"stats": SlotPolicy(persistent=True)}) |
A slot with an expiry |
After setup_middleware() returns |
store.persistence_manager.register_slot_policy("stats", SlotPolicy(persistent=True)) |
A policy decided once the bot is up |
One mark is enough, and it holds for the slot's name from then on. A slot takes one SlotPolicy:
register_slot_policy() raises ValueError for a slot that has one already, the setup's included.
The stats slot from Subscribers and Slots keeps each
player's wins under str(user_id). Key a saved slot by something that is the same after a restart, such as a
user or server id. A plain view's persistence_key is the view's own id unless you pass one or set one in the
class body, a new value each time the view is built, so a slot keyed by it is not found after a restart.
What Is Saved¶
A marked slot is saved as JSON:
| In the slot | After a restart |
|---|---|
Dicts, lists, strings, numbers, True, False, None |
The same |
| A tuple | A list |
An int key, such as 42 |
The string "42", and the save logs an ERROR naming the key. Key by str(user.id) |
A set, or a discord.py object such as a Member |
What was saved before: the slot is not saved, and the save logs an ERROR naming it |
The slot itself set to None, or removed |
Nothing: its row is deleted |
Keep ids rather than discord.py objects:
await self.dispatch_scoped({"target": interaction.user}) # the slot is not saved
await self.dispatch_scoped({"target": interaction.user.id}) # saved
When a Slot Is Written¶
A change is seen when an action, set_scoped(), or a view's seed_initial_state() makes it. The changes waiting go out together, in one write:
- 2 seconds after the last change to a saved slot, or 10 seconds after the first one waiting if changes keep coming.
- When persistence closes.
A slot is written only when what it would save differs from what is saved, so an action that leaves it as it was writes nothing. Unmarked slots are never looked at. A persistent panel's row is written at once (Panels That Survive Restarts).
Expiry¶
from discord.ext import commands
from cascadeui import (
ApplicationPersistence,
PersistenceMiddleware,
SlotPolicy,
SQLiteBackend,
setup_middleware,
)
class TicketBot(commands.Bot):
async def setup_hook(self):
db = SQLiteBackend("cascadeui.db")
await setup_middleware(
PersistenceMiddleware(
backend=db,
application=ApplicationPersistence(
backend=db,
slots={"search_cache": SlotPolicy(persistent=True, ttl_days=7)},
),
bot=self,
),
)
ttl_days=7 saves the slot and removes it 7 days after its last change, from the database and from the store: at
the next start, or by a sweep that runs once a day while the bot is up. The sweep dispatches
APPLICATION_SLOTS_PRUNED naming the slots it removed. A slot that is read but not changed still expires, and the
whole slot goes at once: for the scoped slot, every person's entry.
Only a SlotPolicy sets an expiry. SlotPolicy(ttl_days=7) without persistent=True raises ValueError, since
a slot that is not saved has nothing to expire. A slot with no expiry is kept until you remove it
(Pruning). An expiry needs a backend that can delete expired rows, which all three the
library ships can, and on one that cannot, ApplicationPersistence(slots=...) and register_slot_policy() raise
PersistenceConfigError (Capability Flags).