mirror of
https://github.com/koloideal/Argenta.git
synced 2026-06-10 18:15:28 +03:00
docs
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
|
|
||||||
router = Router(title="User Management")
|
router = Router(title="User Management")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Server Management")
|
router = Router(title="Server Management")
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from argenta.command.flag.defaults import PredefinedFlags
|
|
||||||
from argenta.command import Flags
|
from argenta.command import Flags
|
||||||
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
# Использование предопределенных флагов при создании команды
|
# Использование предопределенных флагов при создании команды
|
||||||
command_flags = Flags([
|
command_flags = Flags([
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from argenta.command import Flag, PossibleValues
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from argenta.command import Flag, PossibleValues
|
||||||
|
|
||||||
# Простой флаг с любыми значениями
|
# Простой флаг с любыми значениями
|
||||||
verbose_flag = Flag(name="verbose")
|
verbose_flag = Flag(name="verbose")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from argenta.command.flag.models import Flag, PossibleValues
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from argenta.command.flag.models import Flag, PossibleValues
|
||||||
|
|
||||||
# Флаг со списком допустимых значений
|
# Флаг со списком допустимых значений
|
||||||
format_flag = Flag(name="format", possible_values=["json", "xml", "csv"])
|
format_flag = Flag(name="format", possible_values=["json", "xml", "csv"])
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from argenta.command import Flags, Flag
|
|
||||||
from argenta import Command
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from argenta import Command
|
||||||
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
# Создание коллекции с флагами
|
# Создание коллекции с флагами
|
||||||
flags = Flags([
|
flags = Flags([
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command import Flags, Flag
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
# Создание коллекции
|
# Создание коллекции
|
||||||
flags: Flags = Flags()
|
flags: Flags = Flags()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command import Flags, Flag
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
# Начальная коллекция
|
# Начальная коллекция
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command import Flags, Flag
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command import Flags, Flag
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command import Flags, Flag
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([
|
||||||
Flag("first"),
|
Flag("first"),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Example")
|
router = Router(title="Example")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag import ValidationStatus
|
from argenta.command.flag import ValidationStatus
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ def validate_handler(response: Response):
|
|||||||
print(f" ? {flag.string_entity}: {flag.input_value} (UNDEFINED)")
|
print(f" ? {flag.string_entity}: {flag.input_value} (UNDEFINED)")
|
||||||
|
|
||||||
# Выводим сводку
|
# Выводим сводку
|
||||||
print(f"\nSummary:")
|
print("\nSummary:")
|
||||||
print(f" Valid flags: {len(valid_flags)}")
|
print(f" Valid flags: {len(valid_flags)}")
|
||||||
print(f" Invalid flags: {len(invalid_flags)}")
|
print(f" Invalid flags: {len(invalid_flags)}")
|
||||||
print(f" Undefined flags: {len(undefined_flags)}")
|
print(f" Undefined flags: {len(undefined_flags)}")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Get Flag Example")
|
router = Router(title="Get Flag Example")
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command.flag import InputFlag, ValidationStatus, InputFlags
|
from argenta.command.flag import InputFlag, InputFlags, ValidationStatus
|
||||||
|
|
||||||
router = Router(title="Add Flag Example")
|
router = Router(title="Add Flag Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta.command.flag import InputFlag, ValidationStatus, InputFlags
|
from argenta.command.flag import InputFlag, InputFlags, ValidationStatus
|
||||||
|
|
||||||
# Создаём коллекцию InputFlags
|
# Создаём коллекцию InputFlags
|
||||||
flags = InputFlags()
|
flags = InputFlags()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Iterate Example")
|
router = Router(title="Iterate Example")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Index Access Example")
|
router = Router(title="Index Access Example")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
router = Router(title="Bool Check Example")
|
router = Router(title="Bool Check Example")
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from argenta.command.flag.flags.models import InputFlags
|
|
||||||
from argenta.command.flag import InputFlag, ValidationStatus
|
from argenta.command.flag import InputFlag, ValidationStatus
|
||||||
|
from argenta.command.flag.flags.models import InputFlags
|
||||||
|
|
||||||
# Создаём первую коллекцию
|
# Создаём первую коллекцию
|
||||||
flags1 = InputFlags([
|
flags1 = InputFlags([
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag import InputFlag, ValidationStatus
|
from argenta.command.flag import InputFlag
|
||||||
|
|
||||||
router = Router(title="Contains Example")
|
router = Router(title="Contains Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from argenta.command import Flag, PossibleValues
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from argenta.command import Flag, PossibleValues
|
||||||
|
|
||||||
# Флаг без значения
|
# Флаг без значения
|
||||||
verbose_flag = Flag(
|
verbose_flag = Flag(
|
||||||
name="verbose",
|
name="verbose",
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from argenta import Command, Response, Router
|
||||||
|
from argenta.command import Flag, Flags
|
||||||
|
from argenta.command.flag.models import ValidationStatus
|
||||||
|
from argenta.di import FromDishka
|
||||||
|
|
||||||
|
from .repository import Priority, Task, TaskRepository
|
||||||
|
|
||||||
|
router = Router(title="Task Manager")
|
||||||
|
|
||||||
|
@router.command(
|
||||||
|
Command(
|
||||||
|
"add-task",
|
||||||
|
description="Add a new task",
|
||||||
|
flags=Flags([
|
||||||
|
Flag("description"),
|
||||||
|
Flag("priority", possible_values=["low", "medium", "high"]),
|
||||||
|
])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
def add_task(response: Response, repo: FromDishka[TaskRepository]):
|
||||||
|
description_flag = response.input_flags.get_flag_by_name("description")
|
||||||
|
|
||||||
|
if not description_flag or not description_flag.input_value:
|
||||||
|
print("Error: --description flag is required.")
|
||||||
|
return
|
||||||
|
task_description = description_flag.input_value
|
||||||
|
|
||||||
|
priority_flag = response.input_flags.get_flag_by_name("priority")
|
||||||
|
|
||||||
|
if priority_flag and priority_flag.status == ValidationStatus.VALID:
|
||||||
|
priority_value = priority_flag.input_value
|
||||||
|
else:
|
||||||
|
priority_value = "medium"
|
||||||
|
|
||||||
|
priority = cast(Priority, priority_value)
|
||||||
|
|
||||||
|
task = Task(description=task_description, priority=priority)
|
||||||
|
repo.add_task(task)
|
||||||
|
print(f"Added task: '{task.description}' with priority '{task.priority}'")
|
||||||
|
|
||||||
|
@router.command(Command("list-tasks", description="List all tasks"))
|
||||||
|
def list_tasks(response: Response, repo: FromDishka[TaskRepository]):
|
||||||
|
tasks = repo.get_all_tasks()
|
||||||
|
if not tasks:
|
||||||
|
print("No tasks found.")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("Tasks:")
|
||||||
|
for i, task in enumerate(tasks, 1):
|
||||||
|
print(f" {i}. {task.description} (Priority: {task.priority})")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from argenta import App, Orchestrator
|
||||||
|
|
||||||
|
from .handlers import router
|
||||||
|
from .provider import TaskProvider
|
||||||
|
|
||||||
|
# 1. Создаем экземпляр приложения
|
||||||
|
app = App(
|
||||||
|
initial_message="Task Manager",
|
||||||
|
prompt="Enter a command: ",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Подключаем роутер с нашими командами
|
||||||
|
app.include_router(router)
|
||||||
|
|
||||||
|
# 3. Создаем и запускаем оркестратор
|
||||||
|
if __name__ == "__main__":
|
||||||
|
orchestrator = Orchestrator(custom_providers=[TaskProvider()])
|
||||||
|
orchestrator.start_polling(app)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from dishka import Provider, Scope, provide
|
||||||
|
|
||||||
|
from .repository import TaskRepository
|
||||||
|
|
||||||
|
|
||||||
|
class TaskProvider(Provider):
|
||||||
|
@provide(scope=Scope.APP)
|
||||||
|
def get_repository(self) -> TaskRepository:
|
||||||
|
return TaskRepository()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
Priority = Literal["low", "medium", "high"]
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Task:
|
||||||
|
description: str
|
||||||
|
priority: Priority = "medium"
|
||||||
|
|
||||||
|
class TaskRepository:
|
||||||
|
def __init__(self):
|
||||||
|
self._tasks: list[Task] = []
|
||||||
|
|
||||||
|
def add_task(self, task: Task):
|
||||||
|
self._tasks.append(task)
|
||||||
|
|
||||||
|
def get_all_tasks(self) -> list[Task]:
|
||||||
|
return self._tasks
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.response import ResponseStatus
|
from argenta.response import ResponseStatus
|
||||||
|
|
||||||
router = Router(title="Example")
|
router = Router(title="Example")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
|
|
||||||
router = Router(title="Data Example")
|
router = Router(title="Data Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
|
|
||||||
router = Router(title="Get Data Example")
|
router = Router(title="Get Data Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
|
|
||||||
router = Router(title="Clear Data Example")
|
router = Router(title="Clear Data Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
|
|
||||||
router = Router(title="Delete Data Example")
|
router = Router(title="Delete Data Example")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from argenta import Router, Command, Response
|
from argenta import Command, Response, Router
|
||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
from argenta.response import ResponseStatus
|
from argenta.response import ResponseStatus
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
from argenta.command.flag import Flag, InputFlag, ValidationStatus, PossibleValues
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from argenta.command.flag import (Flag, InputFlag, PossibleValues,
|
||||||
|
ValidationStatus)
|
||||||
|
|
||||||
# Создаём различные типы флагов
|
# Создаём различные типы флагов
|
||||||
verbose_flag = Flag("verbose", possible_values=PossibleValues.NEITHER)
|
verbose_flag = Flag("verbose", possible_values=PossibleValues.NEITHER)
|
||||||
output_flag = Flag("output", possible_values=PossibleValues.ALL)
|
output_flag = Flag("output", possible_values=PossibleValues.ALL)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from argenta.command.flag import Flag, InputFlag, ValidationStatus, PossibleValues
|
from argenta.command.flag import (Flag, InputFlag, PossibleValues,
|
||||||
|
ValidationStatus)
|
||||||
|
|
||||||
# Создание флага без значения
|
# Создание флага без значения
|
||||||
help_flag = Flag("help", possible_values=PossibleValues.NEITHER)
|
help_flag = Flag("help", possible_values=PossibleValues.NEITHER)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from argenta import InputFlag, ValidationStatus
|
from argenta import InputFlag, ValidationStatus
|
||||||
|
|
||||||
|
|
||||||
def process_input_flag(input_flag: InputFlag) -> None:
|
def process_input_flag(input_flag: InputFlag) -> None:
|
||||||
"""Обрабатывает входной флаг в зависимости от его статуса валидации"""
|
"""Обрабатывает входной флаг в зависимости от его статуса валидации"""
|
||||||
|
|
||||||
|
|||||||
@@ -3,26 +3,49 @@
|
|||||||
Быстрый старт
|
Быстрый старт
|
||||||
********************
|
********************
|
||||||
|
|
||||||
1. **Установка** ``Argenta``
|
В этом руководстве мы создадим простое, но полнофункциональное CLI-приложение «Менеджер задач», которое продемонстрирует ключевые возможности Argenta.
|
||||||
|
|
||||||
|
1. **Установка**
|
||||||
|
|
||||||
.. code-block:: shell
|
.. code-block:: shell
|
||||||
|
|
||||||
pip install argenta
|
pip install argenta
|
||||||
|
|
||||||
2. **Создание обработчиков**. Чтобы зарегистрировать функцию как обработчик команды, используйте декоратор ``@router.command``. Обработчик всегда должен принимать первым аргументом объект ``Response`` (подробнее в :ref:`документации <root_api_response>`).
|
2. **Определение моделей данных и репозитория**
|
||||||
|
|
||||||
.. literalinclude:: ../code_snippets/quickstart/routers.py
|
Сначала определим модели данных для задачи и репозиторий для их хранения. Это будет наша "бизнес-логика".
|
||||||
|
|
||||||
|
.. literalinclude:: ../code_snippets/quickstart/task_manager/repository.py
|
||||||
:language: python
|
:language: python
|
||||||
:linenos:
|
:linenos:
|
||||||
|
|
||||||
3. **Настройка и запуск**. Чтобы подключить обработчики, вызовите метод ``.include_router()`` у экземпляра приложения и передайте в него ваш роутер. Затем создайте оркестратор и вызовите его метод ``.start_polling()``, передав ему приложение.
|
3. **Создание провайдера для DI**
|
||||||
|
|
||||||
.. literalinclude:: ../code_snippets/quickstart/main.py
|
Чтобы Argenta могла внедрять `TaskRepository` в наши обработчики, мы создадим провайдер для `dishka`.
|
||||||
|
|
||||||
|
.. literalinclude:: ../code_snippets/quickstart/task_manager/provider.py
|
||||||
:language: python
|
:language: python
|
||||||
:linenos:
|
:linenos:
|
||||||
|
|
||||||
4. **Запуск**. Теперь приложение можно запустить как обычный Python-скрипт.
|
4. **Создание обработчиков команд**
|
||||||
|
|
||||||
|
Теперь создадим обработчики для команд `add-task` и `list-tasks`. Обратите внимание, как мы используем флаги и внедряем `TaskRepository`.
|
||||||
|
|
||||||
.. image:: https://github.com/koloideal/Argenta/blob/docs/create_docs/imgs/mock_app_preview6.png?raw=true
|
.. literalinclude:: ../code_snippets/quickstart/task_manager/handlers.py
|
||||||
:alt: Quickstart Example
|
:language: python
|
||||||
|
:linenos:
|
||||||
|
|
||||||
|
5. **Сборка и запуск приложения**
|
||||||
|
|
||||||
|
Наконец, соберем все вместе: создадим экземпляр `App`, подключим роутер и провайдер, а затем запустим приложение.
|
||||||
|
|
||||||
|
.. literalinclude:: ../code_snippets/quickstart/task_manager/main.py
|
||||||
|
:language: python
|
||||||
|
:linenos:
|
||||||
|
|
||||||
|
6. **Результат**
|
||||||
|
|
||||||
|
Теперь вы можете запустить `main.py` и взаимодействовать с вашим новым CLI-приложением.
|
||||||
|
|
||||||
|
.. image:: https://github.com/koloideal/Argenta/blob/main/imgs/mock_app_preview4.png?raw=True
|
||||||
|
:alt: Task Manager Example
|
||||||
|
|||||||
Reference in New Issue
Block a user