### Full kasdb Usage Example Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Demonstrates creating a DB instance, setting up event handlers for data retrieval and saving, adding and retrieving data, and updating settings. Includes examples of saving lists and dictionaries, and retrieving specific data keys. ```python from kasdb import DB import json # Создать базу данных для приложения чата chat_db = DB("chat_app", data={ "messages": [], "users": [], "settings": {"theme": "light", "language": "ru"} }) # Настроить обработчики событий def log_get_event(event): print(f"[GET] ключ={event['key']}, файл={event['filename']}") def log_save_event(event): print(f"[SAVE] ключ={event['key']}, значение={event['value']}") chat_db.on("getData", log_get_event) chat_db.on("saveData", log_save_event) # Добавить пользователей chat_db.saveData("users", [ {"id": 1, "name": "Алексей", "status": "online"}, {"id": 2, "name": "Мария", "status": "offline"} ]) # Вывод: [SAVE] ключ=users, значение=[...] # Добавить сообщения messages = [ {"id": 1, "user_id": 1, "text": "Привет!", "timestamp": 1000}, {"id": 2, "user_id": 2, "text": "Привет вам!", "timestamp": 1001} ] chat_db.saveData("messages", messages) # Вывод: [SAVE] ключ=messages, значение=[...] # Получить все данные all_data = chat_db.getData() # Вывод: [GET] ключ=[null], файл=chat_app.db # Получить только пользователей users = chat_db.getData("users") # Вывод: [GET] ключ=users, файл=chat_app.db print(json.dumps(users, indent=2, ensure_ascii=False)) # [ # { # "id": 1, # "name": "Алексей", # "status": "online" # }, # { # "id": 2, # "name": "Мария", # "status": "offline" # } # ] # Обновить настройки chat_db.saveData("settings", {"theme": "dark", "language": "en"}) # Вывод: [SAVE] ключ=settings, значение={...} # Получить новые настройки settings = chat_db.getData("settings") # Вывод: [GET] ключ=settings, файл=chat_app.db print(settings) # {'theme': 'dark', 'language': 'en'} ``` -------------------------------- ### Install KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/00-index.md Install the KasDB library using pip. ```bash pip install kasdb ``` -------------------------------- ### Create, Set, Get, and Delete with kasdb Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Use this pattern for basic application configuration management. Ensure debug mode is enabled for visibility. ```python from kasdb import create, get, set, delete import kasdb.config as config # Включить отладку для видимости операций config.debug = True # Создать базу данных конфигурации приложения create("app_config", ["theme", "language", "volume", "notifications"]) # Установить значения set("app_config", "dark", "theme") set("app_config", "ru", "language") set("app_config", 75, "volume") set("app_config", True, "notifications") # Получить все значения config_data = get("app_config") print(config_data) # {'theme': 'dark', 'language': 'ru', 'volume': 75, 'notifications': True} # Получить конкретный параметр volume = get("app_config", "volume") print(f"Громкость: {volume}%") # Обновить параметр set("app_config", "light", "theme") # Удалить базу данных delete("app_config") ``` -------------------------------- ### Import KasDB DB Class Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Import the DB class from the kasdb library to start using it. ```python from kasdb import DB ``` -------------------------------- ### AsyncDB Full Usage Example Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/05-asyncdb-class-reference.md Demonstrates creating an AsyncDB instance, setting up event handlers for saveData and getData, and performing various data operations like adding tasks, updating counters, and retrieving data. Use this to understand the basic workflow of AsyncDB. ```python from kasdb import AsyncDB import asyncio async def main(): # Создать асинхронную базу данных для приложения задач task_db = AsyncDB("tasks_app", data={ "tasks": [], "completed": 0, "in_progress": 0 }) # Настроить обработчики событий def log_save(event): print(f"[SAVE] {event['key']} = {event['value']}") def log_get(event): print(f"[GET] {event['key']}") task_db.on("saveData", log_save) task_db.on("getData", log_get) # Добавить задачи tasks = [ {"id": 1, "title": "Купить молоко", "status": "pending"}, {"id": 2, "title": "Написать отчёт", "status": "in_progress"} ] await task_db.saveData("tasks", tasks) # Вывод: [SAVE] tasks = [...] # Обновить счётчик завершённых await task_db.saveData("completed", 0) # Вывод: [SAVE] completed = 0 await task_db.saveData("in_progress", 1) # Вывод: [SAVE] in_progress = 1 # Получить все задачи all_tasks = await task_db.getData("tasks") # Вывод: [GET] tasks print(f"Всего задач: {len(all_tasks)}") # Вывод: Всего задач: 2 # Получить счётчики completed = await task_db.getData("completed") in_progress = await task_db.getData("in_progress") # Вывод: # [GET] completed # [GET] in_progress # Получить всё all_data = await task_db.getData() # Вывод: [GET] [null] print(all_data) # { # 'tasks': [...], # 'completed': 0, # 'in_progress': 1 # } asyncio.run(main()) ``` -------------------------------- ### Get All Data and Specific Key from KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Demonstrates how to retrieve all data from a table or a specific value using its key. Errors are printed to the console if the table or key does not exist. ```python from kasdb import create, get, set import kasdb.config as config config.debug = True create("products", ["title", "price", "stock"]) set("products", "Ноутбук", "title") set("products", 59999, "price") set("products", 10, "stock") # Получить все данные all_data = get("products") print(all_data) # {'title': 'Ноутбук', 'price': 59999, 'stock': 10} # Получить значение конкретного ключа price = get("products", "price") print(price) # 59999 # Получить несуществующий ключ — вывод ошибки в консоль get("products", "nonexistent_key") # [RED] базы данных products не существует или же ключ nonexistent_key ненайден ``` -------------------------------- ### Get All Data from Database Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Use this to retrieve all entries from a specified database. Ensure the database exists and is not empty. Debug mode will show success messages. ```python from kasdb import create, get, set import kasdb.config as config config.debug = True create("products", ["title", "price", "stock"]) set("products", "Ноутбук", "title") set("products", 59999, "price") set("products", 10, "stock") # Получить все данные all_data = get("products") print(all_data) # Вывод: {'title': 'Ноутбук', 'price': 59999, 'stock': 10} ``` -------------------------------- ### get Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Retrieves data from a JSON database file. It can fetch all data or the value of a specific key. ```APIDOC ## get ### Description Reads data from a JSON database file. You can get all data at once or the value of a specific key. ### Method Signature ```python def get(db_name: str, key: str = "all") -> dict | Any | None ``` ### Parameters #### Path Parameters - **db_name** (str) - Required - The name of the database (without the .json extension). - **key** (str) - Optional - The key to retrieve a specific value. If the value is "all", it returns all data. Defaults to "all". ### Return Value - If `key="all"`: returns a `dict` with all the data. - If a key is specified: returns the value of that key (can be of any type). - `None` in case of an error (database does not exist, key not found). - If the database is empty (`{}`), a warning is displayed and `None` is returned. ### Behavior - On success and `config.debug=True`, displays a success message in green. - If the database is empty, displays a warning in yellow and returns `None`. - On error, displays an error message in red and returns `None`. ### Examples ```python from kasdb import create, get, set import kasdb.config as config config.debug = True create("products", ["title", "price", "stock"]) set("products", "Ноутбук", "title") set("products", 59999, "price") set("products", 10, "stock") # Get all data all_data = get("products") print(all_data) # Output: {'title': 'Ноутбук', 'price': 59999, 'stock': 10} # Get the value of a specific key price = get("products", "price") print(price) # Output: 59999 # Get a non-existent key result = get("products", "nonexistent_key") # Output error: [RED] database products does not exist or the key nonexistent_key was not found # result = None ``` ``` -------------------------------- ### Centralized Database Management with Wrapper Class Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Implement a wrapper class for centralized database control. This approach simplifies database interactions by providing methods for initialization, getting, setting, and updating data. ```python from kasdb import AsyncDB class Database: """Обёртка для централизованного управления""" def __init__(self, name: str): self.db = AsyncDB(name) async def init(self, initial_data: dict): """Инициализировать базу""" for key, value in initial_data.items(): await self.db.saveData(key, value) async def get(self, key: str): """Получить значение""" return await self.db.getData(key) async def set(self, key: str, value): """Сохранить значение""" await self.db.saveData(key, value) async def update(self, key: str, callback): """Получить, обновить и сохранить""" current = await self.get(key) updated = callback(current) await self.set(key, updated) # Использование db = Database("myapp") await db.init({"users": [], "count": 0}) users = await db.get("users") await db.update("count", lambda c: c + 1) ``` -------------------------------- ### Telegram Bot Integration with AsyncDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/README.md Example of using AsyncDB for a Telegram bot, specifically handling user data. Requires an AsyncDB instance initialized with a name and initial data. ```python from kasdb import AsyncDB db = AsyncDB("bot", data={"users": {}}) async def start_handler(message): users = await db.getData("users") users[str(message.from_user.id)] = message.from_user.first_name await db.saveData("users", users) ``` -------------------------------- ### Enable Debug Logging in KasDB Configuration Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/README.md Set the debug flag to True to enable colored logging output. This is part of the initial configuration setup for KasDB. ```python import kasdb.config as config config.debug = True # Включить цветное логирование ``` -------------------------------- ### get — retrieve data from the database Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Reads data from a JSON database file. You can retrieve all data at once or the value of a specific key. ```APIDOC ## get ### Description Retrieves data from the database. Can fetch all data or a specific key's value. ### Method Signature `get(table_name: str, key: Optional[str] = None)` ### Parameters #### Path Parameters - **table_name** (str) - Required - The name of the table to retrieve data from. - **key** (str) - Optional - The specific key whose value needs to be retrieved. If not provided, all data from the table is returned. ### Request Example ```python # Get all data all_data = get("products") # Get specific key value price = get("products", "price") ``` ### Response #### Success Response - Returns a dictionary containing all data if no key is specified. - Returns the value associated with the specified key if a key is provided. #### Response Example ```json # When retrieving all data { "title": "Ноутбук", "price": 59999, "stock": 10 } # When retrieving a specific key 59999 ``` ### Error Handling - If the table does not exist or the key is not found, an error message is printed to the console. ``` -------------------------------- ### kasdb Procedural API Type Signatures Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/06-types.md Type hints for the core functions in the kasdb procedural API, including create, get, set, delete, if_get, and where_get. ```python # create def create(db_name: str, keys: list) -> None # get def get(db_name: str, key: str = "all") -> dict | Any | None # set def set(db_name: str, data: Any, key: str | None = None) -> None # delete def delete(db_name: str) -> None # if_get def if_get(db_name: str, condition: bool, key: str = "all") -> dict | Any | None # where_get def where_get(db_name: str, key: str, where: Any) -> Any | None ``` -------------------------------- ### Initialize KasDB DB Instances Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Demonstrates creating DB instances with initial data, without data (lazy file creation), and with custom file extensions. ```python from kasdb import DB # Создать базу данных с начальными данными db = DB("myapp", extension=".db", data={"users": [], "count": 0}) # Создать базу данных без начальных данных db = DB("config") # Файл будет создан при первом сохранении данных # Создать базу данных с нестандартным расширением db = DB("cache", extension=".cache") # Файл: cache.cache ``` -------------------------------- ### Initialize AsyncDB with different configurations Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/05-asyncdb-class-reference.md Demonstrates creating an AsyncDB instance with initial data, without initial data, and with a custom file extension. Ensure asyncio is run to execute the main function. ```python from kasdb import AsyncDB import asyncio async def main(): # Create an asynchronous database with initial data db = AsyncDB("async_store", extension=".db", data={"tasks": [], "done": 0}) # Create an asynchronous database without initial data db = AsyncDB("cache") # Create an asynchronous database with a non-standard extension db = AsyncDB("session", extension=".session") asyncio.run(main()) ``` -------------------------------- ### Basic KasDB Script for Settings Management Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/README.md Demonstrates basic usage of KasDB for creating a 'settings' table and setting/getting key-value pairs. Suitable for simple configuration tasks. ```python from kasdb import create, get, set create("settings", ["theme", "volume"]) set("settings", "dark", "theme") set("settings", 80, "volume") print(get("settings")) ``` -------------------------------- ### Public API exposed by kasdb/__init__.py Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/08-module-graph.md The __init__.py file in the kasdb package serves as the main entry point and exports the public API. This includes the DB and AsyncDB classes, as well as several utility functions for database operations. ```APIDOC ## Public API This module exports the following: - `DB` (class) - `AsyncDB` (class) - `create` (function) - `get` (function) - `set` (function) - `delete` (function) - `if_get` (function) - `where_get` (function) ``` -------------------------------- ### Create a New JSON Database with kasdb Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Use the `create` function to initialize a new JSON database file with specified keys. If the file already exists, the operation is ignored. Debug mode should be enabled for output. ```python from kasdb import create import kasdb.config as config config.debug = True # Create a database named "users" with keys "name", "age", "email" create("users", ["name", "age", "email"]) # Output: database users created with data: {'name': None, 'age': None, 'email': None} # Calling again does nothing as the file already exists create("users", ["name", "age", "email"]) ``` -------------------------------- ### DB Constructor Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Initializes a new DB object, optionally creating a file with provided data and extension. ```APIDOC ## DB Constructor ### Description Initializes a new DB object. This constructor allows for the creation of a database file with specified initial data and file extension. If initial data is provided, it will be saved to the file immediately. The file will be created on disk upon the first data save operation if it doesn't already exist. ### Signature ```python def __init__(self, filename: str, extension: str = ".db", data: dict | None = None) -> None ``` ### Parameters #### Parameters - **filename** (str) - Required - The name of the database without the extension. - **extension** (str) - Optional - The file extension. Defaults to ".db". If empty, ".db" is used. - **data** (dict | None) - Optional - Initial data to populate the database. If not None, the data will be saved to the file upon initialization. Defaults to None. ### Behavior - Creates a database object associated with the file `{filename}{extension}`. - If `data` is provided, it is immediately saved to the file. - Initializes `onGetData` and `onSaveData` event handlers to `None`. - The file does not need to exist on disk; it will be created when data is first saved. ### Examples ```python from kasdb import DB # Create a database with initial data db = DB("myapp", extension=".db", data={"users": [], "count": 0}) # Create a database without initial data db = DB("config") # The file will be created on the first save operation # Create a database with a custom extension db = DB("cache", extension=".cache") # File will be named: cache.cache ``` ### Source File - **File**: `kasdb/db.py`, lines 94–105 ``` -------------------------------- ### AsyncDB Constructor Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/05-asyncdb-class-reference.md Initializes an instance of the AsyncDB class. It sets up the database file, optionally with initial data, and prepares it for asynchronous operations. ```APIDOC ## AsyncDB Constructor ### Description Initializes an instance of the AsyncDB class, setting up the database file and optionally loading initial data. This constructor is synchronous but prepares an object for asynchronous operations. ### Signature ```python def __init__(self, filename: str, extension: str = ".db", data: dict | None = None) -> None ``` ### Parameters #### Path Parameters - **filename** (str) - Required - The name of the database file without the extension. - **extension** (str) - Optional - The file extension for the database. Defaults to ".db". If an empty string is provided, ".db" is used. - **data** (dict | None) - Optional - Initial data to populate the database. If provided, this data is synchronously saved to the file upon initialization. Defaults to None. ### Behavior - Creates an asynchronous database object with the filename `{filename}{extension}`. - If `data` is not `None`, it synchronously saves the provided data to the file. - Initializes `onGetData` and `onSaveData` event handlers to `None`. - The file does not need to exist beforehand; it will be created upon the first data save. ### Request Example ```python from kasdb import AsyncDB import asyncio async def main(): # Create an async database with initial data db = AsyncDB("async_store", extension=".db", data={"tasks": [], "done": 0}) # Create an async database without initial data db = AsyncDB("cache") # Create an async database with a custom extension db = AsyncDB("session", extension=".session") asyncio.run(main()) ``` ``` -------------------------------- ### Create a new kasdb database Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Use the `create` function to initialize a new JSON database file with specified keys. If the file already exists, this operation is ignored. Ensure `kasdb` is imported and optionally configure debug output. ```python from kasdb import create import kasdb.config as config config.debug = True # Create a database named "users" with keys "name", "age", "email" create("users", ["name", "age", "email"]) # Output: database users created with data: {'name': None, 'age': None, 'email': None} # Calling again - creation is ignored create("users", ["name", "age", "email"]) # No output, file already exists ``` -------------------------------- ### Get Specific Key Value from Database Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Retrieve the value associated with a specific key from a database. If the key does not exist or the database is not found, an error message will be displayed and None will be returned. Debug mode provides additional output. ```python # Получить значение конкретного ключа price = get("products", "price") print(price) # Вывод: 59999 # Получить несуществующий ключ result = get("products", "nonexistent_key") # Вывод ошибки: [RED] базы данных products не существует или же ключ nonexistent_key ненайден # result = None ``` -------------------------------- ### Initialize DB with Data Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Always initialize data when creating a DB instance to ensure data structures are present. This guarantees that data retrieval operations will succeed. ```python from kasdb import DB # Всегда инициализируйте данные при создании DB db = DB("myapp", data={ "users": [], "settings": {}, "logs": [] }) # Данные гарантированно существуют users = db.getData("users") ``` -------------------------------- ### FastAPI Integration with AsyncDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/README.md Shows how to integrate AsyncDB with FastAPI to serve data. An AsyncDB instance is created, and a FastAPI endpoint retrieves data from it. ```python from kasdb import AsyncDB from fastapi import FastAPI db = AsyncDB("api", data={"items": []}) app = FastAPI() @app.get("/items") async def get_items(): return await db.getData("items") ``` -------------------------------- ### create - Database Creation Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Creates a new JSON database file with specified initial keys. If the file already exists, the operation is ignored. ```APIDOC ## create ### Description Creates a new JSON database file with specified initial keys, setting their values to `None`. If the file already exists, the creation is ignored. ### Method Signature ```python def create(db_name: str, keys: list) -> None ``` ### Parameters #### Path Parameters - **db_name** (str) - Required - The name of the database (without the `.json` extension). - **keys** (list) - Required - A list of strings representing the initial keys, each assigned a value of `None`. ### Returns `None`. Prints a success message to the console if `config.debug=True`. ### Behavior - Creates a file named `{db_name}.json` in the current directory. - Initializes the data structure with the provided keys, all set to `None`. - Ignores creation if the file already exists (does not overwrite). - If `config.debug=True`, prints a success message in green. ### Example Usage ```python from kasdb import create import kasdb.config as config config.debug = True # Create a database named "users" with keys "name", "age", "email" create("users", ["name", "age", "email"]) # Output: database users created with data: {'name': None, 'age': None, 'email': None} # Repeated call - creation is ignored create("users", ["name", "age", "email"]) # No output, file already exists ``` ### Source File - **File**: `kasdb/db.py`, lines 16–25 ``` -------------------------------- ### Synchronous DB Operations with KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Demonstrates creating, saving, and retrieving data using the synchronous DB class. Includes event subscription for saveData and getData operations. ```python from kasdb import DB # Создать базу данных с начальными данными db = DB("myapp", extension=".db", data={"users": [], "count": 0}) # Сохранить данные db.saveData("users", [{"id": 1, "name": "Алексей"}, {"id": 2, "name": "Мария"}]) db.saveData("count", 2) # Получить все данные all_data = db.getData() print(all_data) # {'users': [{'id': 1, 'name': 'Алексей'}, {'id': 2, 'name': 'Мария'}], 'count': 2} # Получить данные по ключу users = db.getData("users") print(users) # [{'id': 1, 'name': 'Алексей'}, {'id': 2, 'name': 'Мария'}] # Подписаться на события def on_save(event): print(f"Сохранено: ключ={event['key']}, значение={event['value']}") def on_get(event): print(f"Получено: ключ={event['key']}, файл={event['filename']}") db.on("saveData", on_save) db.on("getData", on_get) db.saveData("count", 3) # Сохранено: ключ=count, значение=3 db.getData("count") # Получено: ключ=count, файл=myapp.db ``` -------------------------------- ### DB Class with MessagePack Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/00-index.md Utilize the DB class for data persistence using MessagePack. Initialize the DB with a name and initial data structure. ```python from kasdb import DB db = DB("app", data={"users": [], "count": 0}) # Сохранить данные users = db.getData("users") users.append({"id": 1, "name": "Иван"}) db.saveData("users", users) # Получить данные all_users = db.getData("users") print(all_users) ``` -------------------------------- ### Manage Contact List Data with KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Initialize a DB for contacts, set up a save handler, add multiple contacts to a list, update a counter, and retrieve all contacts. Requires the 'kasdb' library. ```python from kasdb import DB import json # Создать базу данных контактов contacts_db = DB("contacts", data={ "contacts": [], "count": 0, "last_updated": None }) # Установить обработчик для логирования сохранений def on_save_contact(event): print(f"[LOG] Сохранено контакты: обновлён ключ '{event['key']}'") contacts_db.on("saveData", on_save_contact) # Добавить первый контакт contacts = contacts_db.getData("contacts") contacts.append({ "id": 1, "name": "Алексей Иванов", "email": "alexey@example.com", "phone": "+79991234567" }) contacts_db.saveData("contacts", contacts) # Добавить второй контакт contacts = contacts_db.getData("contacts") contacts.append({ "id": 2, "name": "Мария Петрова", "email": "maria@example.com", "phone": "+79997654321" }) contacts_db.saveData("contacts", contacts) # Обновить счётчик contacts_db.saveData("count", len(contacts)) # Получить все контакты all_contacts = contacts_db.getData("contacts") print(f"\nВсего контактов: {len(all_contacts)}") for contact in all_contacts: print(f" - {contact['name']} ({contact['email']})") ``` -------------------------------- ### Procedural API with JSON Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/00-index.md Use the procedural API for basic CRUD operations with JSON data. Ensure the 'kasdb' library is imported. ```python from kasdb import create, get, set, delete import kasdb.config as config config.debug = True # Создать базу create("users", ["name", "email"]) # Сохранить данные set("users", "Иван", "name") set("users", "ivan@example.com", "email") # Получить данные data = get("users") print(data) # {'name': 'Иван', 'email': 'ivan@example.com'} # Удалить базу delete("users") ``` -------------------------------- ### Set and Update Data in KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Shows how to write new data to a database table. It can update a specific key's value or overwrite the entire table's content if a dictionary is provided. ```python from kasdb import create, get, set import kasdb.config as config config.debug = True create("settings", ["theme", "language", "volume"]) # Обновить конкретный ключ set("settings", "dark", "theme") # Вывод: данные успешно обновлены set("settings", "ru", "language") set("settings", 80, "volume") print(get("settings")) # {'theme': 'dark', 'language': 'ru', 'volume': 80} # Перезаписать всю базу целиком set("settings", {"theme": "light", "language": "en", "volume": 50}) print(get("settings")) # {'theme': 'light', 'language': 'en', 'volume': 50} ``` -------------------------------- ### Search Article Content with KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Create an article database, set its fields, and search for articles based on tags. Requires the 'kasdb' library. ```python from kasdb import create, set, where_get import kasdb.config as config config.debug = True # Создать базу данных статей create("article", ["title", "content", "tags", "author"]) set("article", "Введение в Python", "title") set("article", "Python — это мощный язык программирования...", "content") set("article", "python,tutorial,programming,beginner", "tags") set("article", "Иван Петров", "author") # Поиск статей с определённым тегом if where_get("article", "tags", "python"): print("Найдена статья с тегом 'python'") tags = get("article", "tags") print(f"Теги: {tags}") # Поиск по другому тегу if where_get("article", "tags", "javascript"): print("Найдена статья с тегом 'javascript'") else: print("Статей с тегом 'javascript' не найдено") ``` -------------------------------- ### Import AsyncDB and asyncio Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/05-asyncdb-class-reference.md Import the necessary AsyncDB class and the asyncio library for asynchronous operations. ```python from kasdb import AsyncDB import asyncio ``` -------------------------------- ### Import kasdb Functions from Main Module Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Import all available kasdb functions directly from the main module. This is the most common way to access the library's functionality. ```python from kasdb import create, get, set, delete, if_get, where_get ``` -------------------------------- ### Import kasdb Functions from Submodule Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Import kasdb functions from the 'db' submodule. This approach can be used if you prefer a more specific import path. ```python from kasdb.db import create, get, set, delete, if_get, where_get ``` -------------------------------- ### kasdb/__init__.py Public API Exports Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/08-module-graph.md This snippet shows the __all__ list from kasdb/__init__.py, which defines the public API exposed by the module. It includes classes and functions intended for external use. ```python __all__ = [ 'DB', 'AsyncDB', 'create', 'get', 'set', 'delete', 'if_get', 'where_get' ] ``` -------------------------------- ### Conditional Data Retrieval with kasdb Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/09-usage-patterns.md Use `if_get` for retrieving data based on conditions, such as user login status or administrative privileges. Debug mode is recommended. ```python from kasdb import create, set, if_get, get import kasdb.config as config config.debug = True # Создать базу данных для сессии пользователя create("session", ["user_id", "token", "is_logged_in", "is_admin"]) set("session", 42, "user_id") set("session", "abc_xyz_123", "token") set("session", True, "is_logged_in") set("session", False, "is_admin") # Получить данные если пользователь залогинен user_id = get("session", "user_id") is_logged_in = get("session", "is_logged_in") if is_logged_in: # Получить все данные только если залогинен session_data = if_get("session", condition=True) print("Сессия активна:", session_data) else: print("Пользователь не залогинен") # Проверить является ли пользователь админом is_admin = if_get("session", condition=True, key="is_admin") if is_admin: print("Пользователь имеет права администратора") ``` -------------------------------- ### Save Data Asynchronously with AsyncDB Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/05-asyncdb-class-reference.md Demonstrates how to asynchronously save or update data in the database using the `saveData` method. Includes subscribing to save events and verifying the saved data. ```python from kasdb import AsyncDB import asyncio async def main(): db = AsyncDB("async_store", data={"tasks": [], "done": 0}) # Подписаться на событие сохранения def on_save(event): print(f"[AsyncDB] Сохранено: {event['key']} = {event['value']}") db.on("saveData", on_save) # Сохранить асинхронно await db.saveData("tasks", ["задача 1", "задача 2", "задача 3"]) # Вывод: [AsyncDB] Сохранено: tasks = ['задача 1', 'задача 2', 'задача 3'] await db.saveData("done", 1) # Вывод: [AsyncDB] Сохранено: done = 1 # Проверить результат all_data = await db.getData() print(all_data) # {'tasks': ['задача 1', 'задача 2', 'задача 3'], 'done': 1} asyncio.run(main()) ``` -------------------------------- ### DB Instance Attributes Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Details the attributes available on a DB instance, including filename, and callbacks for data retrieval and saving. ```APIDOC ## DB Instance Attributes | Attribute | Type | Description | |-------------|-------------------|---------------------------------------------------| | `filename` | `str` | Full filename with extension (e.g., `"myapp.db"`) | | `onGetData` | `Callable` | `None` | Callback function for the `getData` event | | `onSaveData`| `Callable` | `None` | Callback function for the `saveData` event | ``` -------------------------------- ### if_get(db_name: str, condition: bool, key: str = "all") Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/03-functions-reference.md Retrieves data from the database only if the provided condition is met. If the condition is false, no data is returned. ```APIDOC ## if_get db_name: str, condition: bool, key: str = "all" ### Description Retrieves data from the database only if the provided condition is met. If the condition is false, no data is returned. If `config.debug=True`, a message is printed to the console. ### Method `if_get` ### Parameters #### Path Parameters - **db_name** (str) - Required - The name of the database (without the .json extension). - **condition** (bool) - Required - The condition that must be met for data to be retrieved. - **key** (str) - Optional - Defaults to "all". The key to retrieve specific data. If the value is "all", all data is returned. ### Returns - If `condition=True`: returns the data (entire `dict` or the value of the key). - If `condition=False`: returns `None`. ### Behavior - Checks the condition before retrieving data. - If the condition is not met, the database query is not executed. - If `config.debug=True`, prints a success message in green. - If the condition is false, prints a failure message in green (if debugging is enabled). ### Example Usage ```python from kasdb import create, set, if_get import kasdb.config as config config.debug = True create("session", ["user_id", "token", "is_admin"]) set("session", 42, "user_id") set("session", "abc123", "token") set("session", True, "is_admin") is_admin = if_get("session", "is_admin") # Get all data only if the user is an administrator if is_admin: data = if_get("session", condition=True) print(data) # {'user_id': 42, 'token': 'abc123', 'is_admin': True} # Get a specific key based on a condition token = if_get("session", condition=True, key="token") print(token) # abc123 # Condition not met result = if_get("session", condition=False) # Output: condition not met, data not retrieved # result = None ``` ``` -------------------------------- ### Asynchronous AsyncDB Operations with KasDB Source: https://github.com/kasper-studios/kasdb/blob/main/README.md Shows how to use the asynchronous AsyncDB class for non-blocking data operations within an asyncio application. Includes saving, retrieving data, and event subscription. ```python import asyncio from kasdb import AsyncDB async def main(): # Создать асинхронную базу данных с начальными данными db = AsyncDB("async_store", extension=".db", data={"tasks": [], "done": 0}) # Подписаться на события def on_save(event): print(f"[AsyncDB] Сохранено: {event['key']} = {event['value']}") db.on("saveData", on_save) # Сохранить данные асинхронно await db.saveData("tasks", ["задача 1", "задача 2", "задача 3"]) await db.saveData("done", 1) # Получить все данные all_data = await db.getData() print(all_data) # {'tasks': ['задача 1', 'задача 2', 'задача 3'], 'done': 1} # Получить конкретный ключ tasks = await db.getData("tasks") print(tasks) # ['задача 1', 'задача 2', 'задача 3'] asyncio.run(main()) ``` -------------------------------- ### DB.getData Method Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Retrieves data from the database. It can fetch all data or data associated with a specific key. ```APIDOC ## getData(key=None) ### Description Retrieves data from the database. If a `key` is provided, it returns the data associated with that key. If no `key` is provided (or `None`), it returns all data stored in the database. ### Parameters - **key** (str, optional) - The key of the data to retrieve. Defaults to `None` to fetch all data. ### Request Example ```python # Get all data all_data = chat_db.getData() # Get data for a specific key users = chat_db.getData("users") ``` ### Response #### Success Response - **data** (any) - The data retrieved from the database, corresponding to the specified key or all data if no key is provided. ``` -------------------------------- ### Database Operations (kasdb.db) Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/08-module-graph.md The db.py module contains the core logic for database operations, including functions for creating, retrieving, setting, deleting, and conditionally retrieving data. It also defines the DB and AsyncDB classes for managing database interactions. ```APIDOC ## Database Functions ### create - **Description**: Creates a new database with specified keys. - **Parameters**: - `db_name` (str) - The name of the database. - `keys` (list) - A list of keys to initialize the database with. ### get - **Description**: Retrieves data from the database. - **Parameters**: - `db_name` (str) - The name of the database. - `key` (str, optional) - The key of the data to retrieve. Defaults to "all" to retrieve all data. ### set - **Description**: Sets data in the database. - **Parameters**: - `db_name` (str) - The name of the database. - `data` (Any) - The data to set. - `key` (str | None, optional) - The key for the data. If None, data is appended. ### delete - **Description**: Deletes the entire database. - **Parameters**: - `db_name` (str) - The name of the database to delete. ### if_get - **Description**: Retrieves data from the database if a condition is met. - **Parameters**: - `db_name` (str) - The name of the database. - `condition` (bool) - The condition to check. - `key` (str, optional) - The key of the data to retrieve. Defaults to "all". ### where_get - **Description**: Retrieves data from the database based on a specific criteria. - **Parameters**: - `db_name` (str) - The name of the database. - `key` (str) - The key to filter by. - `where` (Any) - The criteria to match. ## Database Classes ### DB - **Description**: Synchronous database class for managing data. - **Methods**: - `__init__`: Initializes the DB instance. - `on`: Sets up the database connection or configuration. - `getData`: Retrieves data from the database. - `saveData`: Saves data to the database. ### AsyncDB - **Description**: Asynchronous database class for managing data. - **Methods**: - `__init__`: Initializes the AsyncDB instance. - `on`: Sets up the asynchronous database connection or configuration. - `getData` (async): Asynchronously retrieves data from the database. - `saveData` (async): Asynchronously saves data to the database. ``` -------------------------------- ### DB.on Method Source: https://github.com/kasper-studios/kasdb/blob/main/_autodocs/04-db-class-reference.md Registers a callback function to be executed when a specific event occurs. ```APIDOC ## on(event_name, callback) ### Description Registers a `callback` function to be invoked when the specified `event_name` occurs. Supported events are `"getData"` and `"saveData"`. ### Parameters - **event_name** (str) - Required - The name of the event to listen for (e.g., `"getData"`, `"saveData"`). - **callback** (Callable) - Required - The function to execute when the event is triggered. The callback function will receive an event object as an argument. ### Event Object Structure - **getData event**: `{"key": str | None, "filename": str}` - **saveData event**: `{"key": str, "value": any}` ### Request Example ```python def log_get_event(event): print(f"[GET] key={event['key']}, filename={event['filename']}") chat_db.on("getData", log_get_event) ``` ```