Update documentation and code snippets

This commit is contained in:
2025-12-02 11:22:31 +03:00
parent 2ff47398ba
commit 7c20bf296b
23 changed files with 63 additions and 62 deletions
+3 -3
View File
@@ -7,15 +7,15 @@ router = Router()
@router.command("get_args") @router.command("get_args")
def get_args(response: Response, argspace: FromDishka[ArgSpace]): def get_args(response: Response, argspace: FromDishka[ArgSpace]):
# Получение всех булевых флагов # Get all boolean flags
boolean_flags = argspace.get_by_type(BooleanArgument) boolean_flags = argspace.get_by_type(BooleanArgument)
print(f"Active flags: {[arg.name for arg in boolean_flags if arg.value]}") print(f"Active flags: {[arg.name for arg in boolean_flags if arg.value]}")
# Получение всех аргументов со значениями # Get all value arguments
value_args = argspace.get_by_type(ValueArgument) value_args = argspace.get_by_type(ValueArgument)
for arg in value_args: for arg in value_args:
print(f"{arg.name} = {arg.value}") print(f"{arg.name} = {arg.value}")
# Подсчет количества аргументов каждого типа # Count arguments of each type
print(f"Boolean arguments: {len(argspace.get_by_type(BooleanArgument))}") print(f"Boolean arguments: {len(argspace.get_by_type(BooleanArgument))}")
print(f"Value arguments: {len(argspace.get_by_type(ValueArgument))}") print(f"Value arguments: {len(argspace.get_by_type(ValueArgument))}")
+2 -2
View File
@@ -1,6 +1,6 @@
from argenta.orchestrator.argparser import ArgParser, ValueArgument from argenta.orchestrator.argparser import ArgParser, ValueArgument
# Создание аргументов # Create arguments
config_arg = ValueArgument( config_arg = ValueArgument(
"config", "config",
help="Path to configuration file", help="Path to configuration file",
@@ -20,7 +20,7 @@ host_arg = ValueArgument(
is_required=True is_required=True
) )
# Регистрация в ArgParser # Register in ArgParser
parser = ArgParser( parser = ArgParser(
processed_args=[config_arg, log_level_arg, host_arg], processed_args=[config_arg, log_level_arg, host_arg],
name="MyApp", name="MyApp",
+2 -2
View File
@@ -1,6 +1,6 @@
from argenta.orchestrator.argparser import ArgParser, BooleanArgument from argenta.orchestrator.argparser import ArgParser, BooleanArgument
# Создание булевых аргументов # Create boolean arguments
verbose_arg = BooleanArgument( verbose_arg = BooleanArgument(
"verbose", "verbose",
help="Enable verbose output" help="Enable verbose output"
@@ -16,7 +16,7 @@ no_cache_arg = BooleanArgument(
help="Disable caching" help="Disable caching"
) )
# Регистрация в ArgParser # Register in ArgParser
parser = ArgParser( parser = ArgParser(
processed_args=[verbose_arg, debug_arg, no_cache_arg], processed_args=[verbose_arg, debug_arg, no_cache_arg],
name="MyApp" name="MyApp"
+2 -2
View File
@@ -1,11 +1,11 @@
from argenta.command import InputCommand from argenta.command import InputCommand
# Парсинг команды без флагов # Parse command without flags
cmd1 = InputCommand.parse("hello") cmd1 = InputCommand.parse("hello")
print(cmd1.trigger) # "hello" print(cmd1.trigger) # "hello"
print(len(cmd1.input_flags)) # 0 print(len(cmd1.input_flags)) # 0
# Парсинг команды с флагами # Parse command with flags
cmd2 = InputCommand.parse("deploy --env prod --force") cmd2 = InputCommand.parse("deploy --env prod --force")
print(cmd2.trigger) # "deploy" print(cmd2.trigger) # "deploy"
print(len(cmd2.input_flags)) # 2 print(len(cmd2.input_flags)) # 2
+4 -4
View File
@@ -2,19 +2,19 @@ import re
from argenta.command.flag.models import Flag, PossibleValues from argenta.command.flag.models import Flag, PossibleValues
# Флаг со списком допустимых значений # Flag with list of allowed values
format_flag = Flag(name="format", possible_values=["json", "xml", "csv"]) format_flag = Flag(name="format", possible_values=["json", "xml", "csv"])
# Валидация значений # Value validation
print(format_flag.validate_input_flag_value("json")) # True print(format_flag.validate_input_flag_value("json")) # True
print(format_flag.validate_input_flag_value("pdf")) # False print(format_flag.validate_input_flag_value("pdf")) # False
# Флаг без значения # Flag without value
help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER) help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER)
print(help_flag.validate_input_flag_value(None)) # True print(help_flag.validate_input_flag_value(None)) # True
print(help_flag.validate_input_flag_value("value")) # False print(help_flag.validate_input_flag_value("value")) # False
# Флаг с регулярным выражением # Flag with regular expression
port_flag = Flag(name="port", possible_values=re.compile(r"^\d{1,5}$")) port_flag = Flag(name="port", possible_values=re.compile(r"^\d{1,5}$"))
print(port_flag.validate_input_flag_value("8080")) # True print(port_flag.validate_input_flag_value("8080")) # True
print(port_flag.validate_input_flag_value("abc")) # False print(port_flag.validate_input_flag_value("abc")) # False
+2 -2
View File
@@ -6,10 +6,10 @@ router = Router(title="Add Flag Example")
@router.command(Command("test", description="Test command")) @router.command(Command("test", description="Test command"))
def test_handler(response: Response): def test_handler(response: Response):
# Создаём новую коллекцию InputFlags # Create new InputFlags collection
new_flags = InputFlags() new_flags = InputFlags()
# Добавляем один флаг # Add one flag
test_flag = InputFlag( test_flag = InputFlag(
name="test", prefix="--", input_value="value", status=ValidationStatus.VALID name="test", prefix="--", input_value="value", status=ValidationStatus.VALID
) )
+3 -3
View File
@@ -1,9 +1,9 @@
from argenta.command.flag import InputFlag, InputFlags, ValidationStatus from argenta.command.flag import InputFlag, InputFlags, ValidationStatus
# Создаём коллекцию InputFlags # Create InputFlags collection
flags = InputFlags() flags = InputFlags()
# Создаём несколько флагов # Create several flags
flag1 = InputFlag( flag1 = InputFlag(
name="option1", prefix="--", input_value="value1", status=ValidationStatus.VALID name="option1", prefix="--", input_value="value1", status=ValidationStatus.VALID
) )
@@ -16,7 +16,7 @@ flag3 = InputFlag(
name="option3", prefix="---", input_value="value3", status=ValidationStatus.VALID name="option3", prefix="---", input_value="value3", status=ValidationStatus.VALID
) )
# Добавляем все флаги одним вызовом # Add all flags in one call
flags.add_flags([flag1, flag2, flag3]) flags.add_flags([flag1, flag2, flag3])
print(f"Total flags: {len(flags.flags)}") print(f"Total flags: {len(flags.flags)}")
+2 -2
View File
@@ -14,7 +14,7 @@ router = Router(title="Bool Check Example")
def action_handler(response: Response): def action_handler(response: Response):
input_flags = response.input_flags input_flags = response.input_flags
# Проверяем наличие флагов # Check for flags presence
if input_flags: if input_flags:
print("Flags were provided:") print("Flags were provided:")
for flag in input_flags: for flag in input_flags:
@@ -22,6 +22,6 @@ def action_handler(response: Response):
else: else:
print("No flags provided, using defaults") print("No flags provided, using defaults")
# Альтернативный способ проверки # Alternative way to check
has_flags = bool(input_flags) has_flags = bool(input_flags)
print(f"\nHas flags: {has_flags}") print(f"\nHas flags: {has_flags}")
+7 -7
View File
@@ -1,7 +1,7 @@
from argenta.command.flag import InputFlag, ValidationStatus from argenta.command.flag import InputFlag, ValidationStatus
from argenta.command.flag.flags.models import InputFlags from argenta.command.flag.flags.models import InputFlags
# Создаём первую коллекцию # Create first collection
flags1 = InputFlags( flags1 = InputFlags(
[ [
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID), InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
@@ -9,7 +9,7 @@ flags1 = InputFlags(
] ]
) )
# Создаём вторую коллекцию с теми же флагами # Create second collection with same flags
flags2 = InputFlags( flags2 = InputFlags(
[ [
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID), InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
@@ -17,7 +17,7 @@ flags2 = InputFlags(
] ]
) )
# Создаём третью коллекцию с другими флагами # Create third collection with different values
flags3 = InputFlags( flags3 = InputFlags(
[ [
InputFlag(name="flag1", input_value="different", status=ValidationStatus.VALID), InputFlag(name="flag1", input_value="different", status=ValidationStatus.VALID),
@@ -25,13 +25,13 @@ flags3 = InputFlags(
] ]
) )
print(f"flags1 == flags2: {flags1 == flags2}") # True (одинаковые имена) print(f"flags1 == flags2: {flags1 == flags2}") # True (same names)
print( print(
f"flags1 == flags3: {flags1 == flags3}" f"flags1 == flags3: {flags1 == flags3}"
) # True (имена одинаковые, значения не учитываются) ) # True (same names, values are not considered)
# Разные коллекции # Different collections
flags4 = InputFlags( flags4 = InputFlags(
[InputFlag(name="flag3", input_value="value3", status=ValidationStatus.VALID)] [InputFlag(name="flag3", input_value="value3", status=ValidationStatus.VALID)]
) )
print(f"flags1 == flags4: {flags1 == flags4}") # False (разные флаги) print(f"flags1 == flags4: {flags1 == flags4}") # False (different flags)
+3 -3
View File
@@ -15,18 +15,18 @@ router = Router(title="Contains Example")
def check_handler(response: Response): def check_handler(response: Response):
input_flags = response.input_flags input_flags = response.input_flags
# Проверяем наличие конкретного флага # Check for specific flag presence
verbose_flag = input_flags.get_flag_by_name("verbose") verbose_flag = input_flags.get_flag_by_name("verbose")
debug_flag = input_flags.get_flag_by_name("debug") debug_flag = input_flags.get_flag_by_name("debug")
# Используем оператор in для проверки # Use 'in' operator for checking
if verbose_flag and verbose_flag in input_flags: if verbose_flag and verbose_flag in input_flags:
print("Verbose flag is present") print("Verbose flag is present")
if debug_flag and debug_flag in input_flags: if debug_flag and debug_flag in input_flags:
print("Debug flag is present") print("Debug flag is present")
# Можно создать флаг для проверки (сравнение идёт по имени) # You can create a flag for checking (comparison is by name)
test_flag = InputFlag(name="verbose", prefix="--", input_value="any", status=None) test_flag = InputFlag(name="verbose", prefix="--", input_value="any", status=None)
if test_flag in input_flags: if test_flag in input_flags:
+4 -4
View File
@@ -15,13 +15,13 @@ class ConnectionProvider(Provider):
conn.close() conn.close()
# 2. Создаем и настраиваем App # 2. Create and configure App
app = App() app = App()
# ... здесь можно добавить роутеры ... # ... you can add routers here ...
# 3. Создаем Orchestrator, передавая наш провайдер # 3. Create Orchestrator, passing our provider
orchestrator = Orchestrator(custom_providers=[ConnectionProvider()]) orchestrator = Orchestrator(custom_providers=[ConnectionProvider()])
# 4. Запускаем приложение # 4. Start the application
if __name__ == "__main__": if __name__ == "__main__":
orchestrator.start_polling(app) orchestrator.start_polling(app)
+10 -10
View File
@@ -1,7 +1,7 @@
from argenta import App, Command, Orchestrator, Router, Response from argenta import App, Command, Orchestrator, Router, Response
from argenta.command import Flag from argenta.command import Flag
# 1. Создание экземпляра приложения и оркестратора # 1. Create app and orchestrator instances
app = App( app = App(
prompt=">> ", prompt=">> ",
initial_message="Simple App", initial_message="Simple App",
@@ -9,28 +9,28 @@ app = App(
) )
orchestrator = Orchestrator() orchestrator = Orchestrator()
# 2. Создание роутера для группировки команд # 2. Create router for grouping commands
main_router = Router(title="Основные команды") main_router = Router(title="Main commands")
# 3. Определение команды и её обработчика # 3. Define command and its handler
@main_router.command( @main_router.command(
Command( Command(
"hello", description="Печатает приветственное сообщение", flags=Flag("name") "hello", description="Prints greeting message", flags=Flag("name")
) )
) )
def hello_handler(response: Response): def hello_handler(response: Response):
"""Этот обработчик будет вызван для команды 'hello'.""" """This handler will be called for 'hello' command."""
name = response.input_flags.get_flag_by_name("name") name = response.input_flags.get_flag_by_name("name")
if name: if name:
print(f"Привет, {name.input_value}!") print(f"Hello, {name.input_value}!")
else: else:
print("Привет, мир!") print("Hello, world!")
# 4. Подключение роутера к приложению # 4. Include router to application
app.include_router(main_router) app.include_router(main_router)
# 5. Запуск приложения # 5. Start application
if __name__ == "__main__": if __name__ == "__main__":
orchestrator.start_polling(app) orchestrator.start_polling(app)
@@ -3,16 +3,16 @@ from argenta import App, Orchestrator
from .handlers import router from .handlers import router
from .provider import TaskProvider from .provider import TaskProvider
# 1. Создаем экземпляр приложения и оркестратора # 1. Create app and orchestrator instances
app = App( app = App(
initial_message="Task Manager", initial_message="Task Manager",
prompt="Enter a command: ", prompt="Enter a command: ",
) )
orchestrator = Orchestrator(custom_providers=[TaskProvider()]) orchestrator = Orchestrator(custom_providers=[TaskProvider()])
# 2. Подключаем роутер с нашими командами # 2. Include router with our commands
app.include_router(router) app.include_router(router)
# 3. Запускаем поллинг через оркестратор # 3. Start polling via orchestrator
if __name__ == "__main__": if __name__ == "__main__":
orchestrator.start_polling(app) orchestrator.start_polling(app)
+3 -3
View File
@@ -1,10 +1,10 @@
from argenta import Response, Router from argenta import Response, Router
# Для этого роутера перехват stdout будет отключен # For this router stdout redirect will be disabled
interactive_router = Router(disable_redirect_stdout=True) interactive_router = Router(disable_redirect_stdout=True)
@interactive_router.command("ask") @interactive_router.command("ask")
def ask_name(response: Response): def ask_name(response: Response):
name = input("Как вас зовут? ") name = input("What is your name? ")
print(f"Приятно познакомиться, {name}!") print(f"Nice to meet you, {name}!")
@@ -1,5 +1,5 @@
from argenta import App from argenta import App
from argenta.app import StaticDividingLine from argenta.app import StaticDividingLine
# Все роутеры по умолчанию будут использовать статическую линию длиной 50 символов # All routers will use static line with length 50 by default
app = App(dividing_line=StaticDividingLine(length=50)) app = App(dividing_line=StaticDividingLine(length=50))
+2 -2
View File
@@ -5,7 +5,7 @@ router = Router(title="Data Example")
@router.command(Command("set", description="Set data")) @router.command(Command("set", description="Set data"))
def set_handler(response: Response): def set_handler(response: Response):
# Обновляем глобальное хранилище данных # Update global data storage
response.update_data( response.update_data(
{ {
"user_name": "John", "user_name": "John",
@@ -18,7 +18,7 @@ def set_handler(response: Response):
@router.command(Command("show", description="Show data")) @router.command(Command("show", description="Show data"))
def show_handler(response: Response): def show_handler(response: Response):
# Получаем данные из глобального хранилища # Get data from global storage
data = response.get_data() data = response.get_data()
if "user_name" in data: if "user_name" in data:
print(f"User: {data['user_name']}") print(f"User: {data['user_name']}")
+1 -1
View File
@@ -5,7 +5,7 @@ router = Router(title="Get Data Example")
@router.command(Command("info", description="Show all stored data")) @router.command(Command("info", description="Show all stored data"))
def info_handler(response: Response): def info_handler(response: Response):
# Получаем все данные из глобального хранилища # Get all data from global storage
all_data = response.get_data() all_data = response.get_data()
if all_data: if all_data:
+1 -1
View File
@@ -5,7 +5,7 @@ router = Router(title="Clear Data Example")
@router.command(Command("clear", description="Clear all stored data")) @router.command(Command("clear", description="Clear all stored data"))
def clear_handler(response: Response): def clear_handler(response: Response):
# Очищаем всё хранилище данных # Clear all data storage
response.clear_data() response.clear_data()
print("All data cleared") print("All data cleared")
+2 -2
View File
@@ -17,12 +17,12 @@ def store_handler(response: Response):
@router.command(Command("remove", description="Remove specific key")) @router.command(Command("remove", description="Remove specific key"))
def remove_handler(response: Response): def remove_handler(response: Response):
# Удаляем конкретный ключ из хранилища # Delete specific key from storage
try: try:
response.delete_from_data("temp_key") response.delete_from_data("temp_key")
print("Key 'temp_key' deleted") print("Key 'temp_key' deleted")
# Проверяем, что осталось # Check what remains
remaining = response.get_data() remaining = response.get_data()
print(f"Remaining keys: {list(remaining.keys())}") print(f"Remaining keys: {list(remaining.keys())}")
except KeyError: except KeyError:
+2 -1
View File
@@ -68,6 +68,7 @@ Router
Выбрасывается, если триггер команды в ``Command`` содержит пробелы. Триггеры должны быть одним словом. Выбрасывается, если триггер команды в ``Command`` содержит пробелы. Триггеры должны быть одним словом.
**Неправильно:** ``Command("add user")`` **Неправильно:** ``Command("add user")``
**Правильно:** ``Command("add-user")`` **Правильно:** ``Command("add-user")``
.. py:exception:: RepeatedFlagNameException .. py:exception:: RepeatedFlagNameException
@@ -81,7 +82,7 @@ Router
Command("send", flags=[ Command("send", flags=[
Flag("recipient"), Flag("recipient"),
Flag("recipient") Flag("recipient") # Duplicate!
]) ])
.. py:exception:: RequiredArgumentNotPassedException .. py:exception:: RequiredArgumentNotPassedException
+1 -1
View File
@@ -41,7 +41,7 @@
В основе DI в Argenta лежат **провайдеры** и **контейнер**. В основе DI в Argenta лежат **провайдеры** и **контейнер**.
* **Провайдер (Provider)** — это "рецепт", который объясняет, как создавать и настраивать ту или иную зависимость (например, подключение к БД, API-клиент или любой другой сервис). * **Провайдер (``Provider``)** — это "рецепт", который объясняет, как создавать и настраивать ту или иную зависимость (например, подключение к БД, API-клиент или любой другой сервис).
* **Контейнер (IoC Container)** — это "фабрика", которая хранит все рецепты (провайдеры) и по запросу создаёт и выдаёт готовые зависимости. * **Контейнер (IoC Container)** — это "фабрика", которая хранит все рецепты (провайдеры) и по запросу создаёт и выдаёт готовые зависимости.
----- -----
+1 -1
View File
@@ -51,7 +51,7 @@ Argenta выбрасывает исключения в пограничных с
Исключение выбрасывается, если пользователь ввёл команду с повторяющимися флагами. Два флага (:ref:`InputFlag <root_api_command_input_flag>`) считаются одинаковыми, если у них совпадают имена. Подробнее о флагах и их синтаксисе — в разделе :ref:`Flags <root_flags>`. Исключение выбрасывается, если пользователь ввёл команду с повторяющимися флагами. Два флага (:ref:`InputFlag <root_api_command_input_flag>`) считаются одинаковыми, если у них совпадают имена. Подробнее о флагах и их синтаксисе — в разделе :ref:`Flags <root_flags>`.
.. note:: .. note::
Сравнение на равенство у регистрируемых флагов(Flag) происходит иначе, подробнее в :ref:`Flag <root_flags>`. Сравнение на равенство у регистрируемых флагов (``Flag``) происходит иначе, подробнее в :ref:`Flag <root_flags>`.
Стандартный хэндлер выводит в консоль Стандартный хэндлер выводит в консоль
+2 -2
View File
@@ -67,11 +67,11 @@
``Argenta`` поддерживает два типа разделителей, которые настраиваются при инициализации ``App``: ``Argenta`` поддерживает два типа разделителей, которые настраиваются при инициализации ``App``:
1. **DynamicDividingLine()** 1. **``DynamicDividingLine()``**
* Поведение по умолчанию. Длина линии динамически подстраивается под самый длинный текст в выводе. * Поведение по умолчанию. Длина линии динамически подстраивается под самый длинный текст в выводе.
* Требует включённого перехвата ``stdout`` (``disable_redirect_stdout=False`` в роутере). * Требует включённого перехвата ``stdout`` (``disable_redirect_stdout=False`` в роутере).
2. **StaticDividingLine(length: int = 25)** 2. **``StaticDividingLine(length: int = 25)``**
* Линия имеет фиксированную длину (по умолчанию 25 символов), которую можно задать через аргумент ``length``. * Линия имеет фиксированную длину (по умолчанию 25 символов), которую можно задать через аргумент ``length``.
* Используется принудительно для роутеров с ``disable_redirect_stdout=True``, так как без перехвата вывода невозможно определить динамическую длину. * Используется принудительно для роутеров с ``disable_redirect_stdout=True``, так как без перехвата вывода невозможно определить динамическую длину.