Сховища#

Вбудоване сховище#

MemoryStorage#

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

Сховище кінцевого автомату за замовчуванням, зберігає всі дані в dict і забуває все під час вимкнення

Попередження

Не рекомендується використовувати на production, оскільки, Ви втратите всі дані під час перезапуску бота

__init__() None[source]#

RedisStorage#

class aiogram.fsm.storage.redis.RedisStorage(redis: ~redis.asyncio.client.Redis, key_builder: ~aiogram.fsm.storage.base.KeyBuilder | None = None, state_ttl: int | ~datetime.timedelta | None = None, data_ttl: int | ~datetime.timedelta | None = None, json_loads: ~typing.Callable[[...], ~typing.Any] = <function loads>, json_dumps: ~typing.Callable[[...], str] = <function dumps>)[source]#

Redis storage required redis package installed (pip install redis)

__init__(redis: ~redis.asyncio.client.Redis, key_builder: ~aiogram.fsm.storage.base.KeyBuilder | None = None, state_ttl: int | ~datetime.timedelta | None = None, data_ttl: int | ~datetime.timedelta | None = None, json_loads: ~typing.Callable[[...], ~typing.Any] = <function loads>, json_dumps: ~typing.Callable[[...], str] = <function dumps>) None[source]#
Параметри:
  • redis – Instance of Redis connection

  • key_builder – builder that helps to convert contextual key to string

  • state_ttl – TTL for state records

  • data_ttl – TTL for data records

classmethod from_url(url: str, connection_kwargs: Dict[str, Any] | None = None, **kwargs: Any) RedisStorage[source]#

Create an instance of RedisStorage with specifying the connection string

Параметри:
  • url – for example redis://user:password@host:port/db

  • connection_kwargs – see redis docs

  • kwargs – arguments to be passed to RedisStorage

Повертає:

екземпляр класу 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.

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

Build key to be used in storage’s db queries

Параметри:
  • key – contextual key

  • part – part of the record

Повертає:

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

Параметри:
  • key – contextual key

  • part – part of the record

Повертає:

key to be used in storage’s db queries

Написання власних сховищ#

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

Основний клас для всіх сховищ кінцевого автомату

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

Установити стан для вказаного ключа

Параметри:
  • key – ключ сховища

  • state – новий стан

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

Отримання стану ключа

Параметри:

key – ключ сховища

Повертає:

поточний стан

abstract async set_data(key: StorageKey, data: Dict[str, Any]) None[source]#

Запис даних (заміна)

Параметри:
  • key – ключ сховища

  • data – нові дані

abstract async get_data(key: StorageKey) Dict[str, Any][source]#

Отримання поточних даних для ключа

Параметри:

key – ключ сховища

Повертає:

нинішні дані

async update_data(key: StorageKey, data: Dict[str, Any]) Dict[str, Any][source]#

Дата оновлення в сховищі для ключа (наприклад, dict.update)

Параметри:
  • key – ключ сховища

  • data – неповні дані

Повертає:

нові дані

abstract async close() None[source]#

Закриття сховища (підключення до бази даних, файлу тощо)