Storages

Storages out of the box

MemoryStorage

class aiogram.fsm.storage.memory.MemoryStorage[source]

Default FSM storage, stores all data in dict and loss everything on shutdown

Warning

Is not recommended using in production in due to you will lose all data when your bot restarts

__init__() None[source]

RedisStorage

MongoStorage

KeyBuilder

Keys inside Redis and Mongo storages can be customized via key builders:

class aiogram.fsm.storage.base.KeyBuilder[source]

Base class for key builder.

abstractmethod build(key: StorageKey, part: Literal['data', 'state', 'lock'] | None = None) str[source]

Build key to be used in storage’s db queries

Parameters:
  • key – contextual key

  • part – part of the record

Returns:

key to be used in storage’s db queries

class aiogram.fsm.storage.base.DefaultKeyBuilder(*, prefix: str = 'fsm', separator: str = ':', with_bot_id: bool = False, with_business_connection_id: bool = False, with_destiny: bool = False)[source]

Simple key builder with default prefix.

Generates a colon-joined string with prefix, chat_id, user_id, optional bot_id, business_connection_id, destiny and field.

Format:

<prefix>:<bot_id?>:<business_connection_id?>:<chat_id>:<user_id>:<destiny?>:<field?>

build(key: StorageKey, part: Literal['data', 'state', 'lock'] | None = None) str[source]

Build key to be used in storage’s db queries

Parameters:
  • key – contextual key

  • part – part of the record

Returns:

key to be used in storage’s db queries

Writing own storages

class aiogram.fsm.storage.base.BaseStorage[source]

Base class for all FSM storages

abstractmethod async set_state(key: StorageKey, state: str | State | None = None) None[source]

Set state for specified key

Parameters:
  • key – storage key

  • state – new state

abstractmethod async get_state(key: StorageKey) str | None[source]

Get key state

Parameters:

key – storage key

Returns:

current state

abstractmethod async set_data(key: StorageKey, data: Mapping[str, Any]) None[source]

Write data (replace)

Parameters:
  • key – storage key

  • data – new data

abstractmethod async get_data(key: StorageKey) dict[str, Any][source]

Get current data for key

Parameters:

key – storage key

Returns:

current data

async update_data(key: StorageKey, data: Mapping[str, Any]) dict[str, Any][source]

Update date in the storage for key (like dict.update)

Parameters:
  • key – storage key

  • data – partial data

Returns:

new data

abstractmethod async close() None[source]

Close storage (database connection, file or etc.)