Утилиты
Транспорт и разбор вывода: то, что используется всеми сущностями.
RacRecord
Тип одной записи вывода RAC — то, что возвращают все методы чтения:
type RacRecord = dict[str, str | int]
Ключи соответствуют полям вывода RAC, дефисы заменены на подчёркивания,
десятичные значения приведены к int. Именно он указан в аннотациях методов
вида -> list[RacRecord] и -> RacRecord.
RacRecord
RacRecord = dict[str, str | int]
Client
Client
Client(rac_path: Path | str)
Путь к исполняемому файлу rac.
Source code in src/raclib/_shared.py
| def __init__(self, rac_path: Path | str):
self.rac_path = Path(rac_path).expanduser()
|
rac_path
instance-attribute
rac_path = Path(rac_path).expanduser()
RawOutput
Результат выполнения команды. Позволяет получить сырой текст или разобрать его.
output = session.exec("cluster list")
output.to_str() # исходный текст
output.to_list() # list[dict]
output.to_dict() # последняя запись
output.to_dataclass(MyRow) # одна запись как dataclass
output.to_list_of_dataclass(Row) # все записи как dataclass
RawOutput
Результат выполнения команды RAC с методами разбора.
Source code in src/raclib/_shared.py
| def __init__(self, output: str) -> None:
self.output = output
|
output
instance-attribute
to_str
Source code in src/raclib/_shared.py
| def to_str(self) -> str:
return self.output.strip()
|
to_dict
to_dict() -> dict[str, str | int]
Source code in src/raclib/_shared.py
| def to_dict(self) -> dict[str, str | int]:
return to_record(self.output)
|
to_dataclass
to_dataclass(dc: type[T]) -> T
Source code in src/raclib/_shared.py
| def to_dataclass(self, dc: type[T]) -> T:
return dc(**self.to_dict())
|
to_list_of_dataclass
to_list_of_dataclass(dc: type[T]) -> list[T]
Source code in src/raclib/_shared.py
| def to_list_of_dataclass(self, dc: type[T]) -> list[T]:
return [dc(**entry) for entry in self.to_list()]
|
to_list
to_list() -> list[dict[str, str | int]]
Source code in src/raclib/_shared.py
| def to_list(self) -> list[dict[str, str | int]]:
return to_records(self.output)
|
Session
Session
Session(client: Client, host: str = 'localhost', port: int = 1545, timeout: float | None = None, encoding: str | None = None, new_window: bool = False, debug: bool = False)
Сессия администрирования: одна пара host:port сервера 1С.
:param host: хост сервера администрирования.
:param port: порт сервера администрирования (по умолчанию 1545).
:param timeout: предел ожидания ответа RAC в секундах. None — без
ограничения. Настоятельно рекомендуется задавать: без таймаута
недоступный кластер подвесит вызывающий поток навсегда.
:param encoding: кодировка вывода RAC. По умолчанию подбирается по
платформе (cp866 на Windows, utf-8 в остальных случаях).
:param new_window: не показывать окно консоли при запуске RAC на Windows.
:param debug: печатать argv и вывод RAC.
Source code in src/raclib/session.py
| def __init__(
self,
client: Client,
host: str = "localhost",
port: int = 1545,
timeout: float | None = None,
encoding: str | None = None,
new_window: bool = False,
debug: bool = False,
):
self.client = client
self.host = host
self.port = port
self.timeout = timeout
self.encoding = resolve_encoding(encoding)
self.new_window = new_window
self.debug = debug
|
client
instance-attribute
timeout
instance-attribute
encoding
instance-attribute
encoding = resolve_encoding(encoding)
new_window
instance-attribute
exec
Выполняет команду RAC и возвращает её вывод.
:raises RACNotFoundError: файл rac не найден или не исполняем.
:raises RACTimeoutError: RAC не ответил за self.timeout секунд.
:raises raclib.errors.UnknownError: RAC вернул незнакомую ошибку.
Source code in src/raclib/session.py
| def exec(self, command: Command | str) -> RawOutput:
"""Выполняет команду RAC и возвращает её вывод.
:raises RACNotFoundError: файл ``rac`` не найден или не исполняем.
:raises RACTimeoutError: RAC не ответил за ``self.timeout`` секунд.
:raises raclib.errors.UnknownError: RAC вернул незнакомую ошибку.
"""
return RawOutput(self._execute(command).stdout)
|
call
call(command: Command | str) -> None
Выполняет команду, отбрасывая вывод.
Source code in src/raclib/session.py
| def call(self, command: Command | str) -> None:
"""Выполняет команду, отбрасывая вывод."""
self._execute(command)
|
_execute
_execute(command: Command | str) -> CommandResult
Source code in src/raclib/session.py
| def _execute(self, command: Command | str) -> CommandResult:
validate_rac_path(self.client.rac_path)
args = [f"{self.host}:{self.port}", *_command_args(command)]
if self.debug:
print("[DEBUG]", args)
try:
result = run_rac(
self.client.rac_path,
args,
timeout=self.timeout,
encoding=self.encoding,
creationflags=_creation_flags(self.new_window),
)
except subprocess.TimeoutExpired:
raise RACTimeoutError(self.timeout or 0) from None
except FileNotFoundError as exc:
raise RACInvocationError(
f"Не удалось запустить RAC по пути {self.client.rac_path}: {exc}"
) from exc
except OSError as exc:
raise RACInvocationError(
f"Не удалось запустить RAC по пути {self.client.rac_path}: {exc}"
) from exc
if result.returncode != 0:
if self.debug:
print("[DEBUG]", result.stderr)
raise errors.handler(result.stderr) from None
if self.debug:
print(result.stdout)
return result
|
Ошибки
Все исключения библиотеки. Разбор сообщений RAC выполняет raclib.errors.handler.
RACNotFoundError
RACNotFoundError(message: str | None = None)
Bases: FileNotFoundError
Исполняемый файл rac не найден.
Историческое имя, используется в публичном API.
Source code in src/raclib/_shared.py
| def __init__(self, message: str | None = None):
super().__init__(message or "RAC CLI not found. Check client params")
|
RACTimeoutError
RACTimeoutError(timeout: float)
Bases: TimeoutError
RAC не ответил за отведённое время.
Source code in src/raclib/_shared.py
| def __init__(self, timeout: float):
super().__init__(
f"RAC не ответил за {timeout} с. "
"Проверьте доступность сервера администрирования "
"или увеличьте значение timeout"
)
|
UnknownError
UnknownError(stderr: str)
Bases: Exception
RAC вернул ошибку, которой нет в таблице соответствий.
Source code in src/raclib/errors.py
| def __init__(self, stderr: str):
lines = [line.strip() for line in stderr.splitlines() if line.strip()]
self.stderr = stderr
super().__init__("\n".join(lines) if lines else stderr.strip())
|
ClusterNotFoundError
ClusterNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Кластер с указанным идентификатором не найден")
|
ClustersNotFoundError
ClustersNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Не найдено ни одного кластера")
|
InfobaseNotFoundError
InfobaseNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Информационная база с указанным идентификатором не найдена")
|
AgentAdminNotFoundError
AgentAdminNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Администратор кластера серверов 1С:Предприятия не найден")
|
AgentAdminsNotFoundError
AgentAdminsNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Не найдено ни одного администратора агента кластера")
|
CounterNotFoundError
CounterNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Счетчик с указанным идентификатором не найден")
|
LimitNotFoundError
LimitNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Ограничение ресурсов с указанным идентификатором не найдено")
|
RuleNotFoundError
RuleNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Требование размещения с указанным идентификатором не найдено")
|
InfobaseCredentialsError
InfobaseCredentialsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Недостаточно прав пользователя на информационную базу")
|
ClusterCredentialsError
ClusterCredentialsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Администратор кластера не аутентифицирован")
|
AgentCredentialsError
AgentCredentialsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"Администратор агента кластера не аутентифицирован. Передайте корректные данные авторизации администратора агента кластера."
)
|
CentralServerCredentialsError
CentralServerCredentialsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Администратор центрального сервера не аутентифицирован.")
|
AgentAdminCreateError
AgentAdminCreateError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"В кластере не остается ни одного администратора с разрешенной аутентификацией паролем"
)
|
ConnectionError
ConnectionError(stderr: str, index: int = 0)
Bases: ConnectionError
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"Ошибка соединения с сервером администрирования. Проверьте настройки подключения"
)
|
CreateInfobaseParamsError
CreateInfobaseParamsError(stderr: str, index: int = 2)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 2):
super().__init__(_line(stderr, index))
|
DatabaseConnectionError
DatabaseConnectionError(stderr: str, index: int = 2)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 2):
super().__init__(_line(stderr, index))
|
DatabaseError
DatabaseError(stderr: str, index: int = 3)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 3):
super().__init__(_line(stderr, index))
|
InfobaseDatabaseNotFoundError
InfobaseDatabaseNotFoundError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"База данных не найдена на сервере баз данных. Задайте create_database значение в True"
)
|
InfobaseAlreadyExistsError
InfobaseAlreadyExistsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"Информационная база уже зарегистрирована в кластере серверов 1С:Предприятия"
)
|
ServerAlreadyExistsError
ServerAlreadyExistsError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Рабочий сервер уже зарегистрирован в кластере")
|
ServerIPRangeError
ServerIPRangeError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Левая граница диапазона IP портов больше правой")
|
ServerIsMainError
ServerIsMainError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Рабочий сервер является центральным. Удаление невозможно")
|
ServerNotCentralError
ServerNotCentralError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(_line(stderr, index))
|
IncorrectVersionError
IncorrectVersionError(stderr: str, index: int = 1)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 1):
super().__init__(_line(stderr, index))
|
ParamError
ParamError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(_line(stderr, index))
|
PortConflictError
PortConflictError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__(
"Запуск рабочего процесса не возможен из-за конфликта IP портов"
)
|
UnknownHostError
UnknownHostError(stderr: str, index: int = 0)
Bases: Exception
Source code in src/raclib/errors.py
| def __init__(self, stderr: str, index: int = 0):
super().__init__("Компьютер отсутствует в сети или недоступен")
|