Python API Weblate¶
Установка¶
Python API поставляется отдельно как пакет Weblate Client:
pip install wlc
wlc¶
Модуль wlc предоставляет клиент API Weblate, объекты API, возвращаемые клиентом, и исключения, вызываемые при типичных сбоях API.
Weblate¶
Класс Weblate является основной точкой входа API. Его непосредственное создание не загружает файлы конфигурации клиента Weblate или переменные окружения WLC_*; его настройки подключения поступают из предоставленных аргументов:
from wlc import Weblate
client = Weblate(
url="https://hosted.weblate.org/api/",
key="APIKEY",
)
projects = list(client.list_projects())
Чтобы использовать обнаружение файлов конфигурации и окружения, явно загрузите WeblateConfig и передайте его клиенту:
from wlc import Weblate
from wlc.config import WeblateConfig
config = WeblateConfig()
config.load()
client = Weblate(config=config)
Клиент Python следует той же политике URL, учётных данных и транспорта, что и клиент командной строки, см. Модель безопасности. Прямые потребители API остаются ответственными за безопасное отображение и хранение возвращаемых значений.
- class wlc.Weblate(*, key: str = '', url: str = 'http://127.0.0.1:8000/api/', config: WeblateConfig | None = None, retries: int = 0, status_forcelist: Collection[int] | None = None, allowed_methods: Collection[str] | None = None, backoff_factor: float = 0, timeout: int = 300, allow_insecure_http: bool = False, allow_insecure_ssl: bool = False)¶
Weblate API wrapper object.
- Параметры:
key – API key used for authenticated requests.
url – API server URL. The URL should point to the Weblate API root.
config – Configuration object. When supplied, it overrides the other connection and request options.
retries – Total number of HTTP retries.
status_forcelist – HTTP status codes that should trigger retries.
allowed_methods – HTTP methods that may be retried.
backoff_factor – Retry backoff factor passed to urllib3.
timeout – HTTP request timeout in seconds.
allow_insecure_http – Allow API keys over non-local
http://URLs.allow_insecure_ssl – Disable TLS certificate verification.
When an API key is configured, non-local
http://URLs are rejected by default. Use HTTPS, loopback HTTP for local development, or setallow_insecure_httponly for legacy deployments where HTTPS is not available. Credentials embedded in API URLs are not supported; configure an API key instead.- add_source_string(*, project: str, component: str, msgid: str, msgstr: str | list[str], source_language: str | None = None) dict[str, Any]¶
Add a source string to a monolingual base file.
- create_component(project: str, *, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None, **kwargs: object) dict[str, Any]¶
Create a new component for project in the instance.
- create_language(*, code: str, name: str, direction: str = 'ltr', plural: dict[str, Any] | None = None) dict[str, Any]¶
Create a new language.
- create_project(*, name: str, slug: str, website: str, source_language_name: str | None = None, source_language_code: str | None = None) dict[str, Any]¶
Create a new project in the instance.
- get(path: str, *, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None) str | int | float | bool | list[JSONValue] | dict[str, JSONValue] | None¶
Perform GET request on the API.
- get_object(path: str) Project | Component | Translation | Unit¶
Return object based on path.
Operates on (project, component or translation objects.
- get_translation(path: str) Translation¶
Return translation of given path.
- invoke_request(method: str, path: str, *, data: Mapping[str, object] | None = None, files: Mapping[str, str | bytes | BinaryIO | TextIO | tuple[str | None, str | bytes | BinaryIO | TextIO] | tuple[str | None, str | bytes | BinaryIO | TextIO, str] | tuple[str | None, str | bytes | BinaryIO | TextIO, str, Mapping[str, str]]] | None = None, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None) Response¶
Construct request object.
- list_translations(path: str = 'translations/') Iterator[Translation]¶
List translations in the instance.
- list_units(path: str, *, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None) Iterator[Unit]¶
List units in the instance.
- post(path: str, *, files: Mapping[str, str | bytes | BinaryIO | TextIO | tuple[str | None, str | bytes | BinaryIO | TextIO] | tuple[str | None, str | bytes | BinaryIO | TextIO, str] | tuple[str | None, str | bytes | BinaryIO | TextIO, str, Mapping[str, str]]] | None = None, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None, **kwargs: object) dict[str, Any]¶
Perform POST request on the API.
- raw_request(method: str, path: str, *, data: Mapping[str, object] | None = None, files: Mapping[str, str | bytes | BinaryIO | TextIO | tuple[str | None, str | bytes | BinaryIO | TextIO] | tuple[str | None, str | bytes | BinaryIO | TextIO, str] | tuple[str | None, str | bytes | BinaryIO | TextIO, str, Mapping[str, str]]] | None = None, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None) bytes¶
Construct request object and returns raw content.
- request(method: str, path: str, *, data: Mapping[str, object] | None = None, files: Mapping[str, str | bytes | BinaryIO | TextIO | tuple[str | None, str | bytes | BinaryIO | TextIO] | tuple[str | None, str | bytes | BinaryIO | TextIO, str] | tuple[str | None, str | bytes | BinaryIO | TextIO, str, Mapping[str, str]]] | None = None, params: Mapping[str, str | bytes | int | float | Iterable[str | bytes | int | float] | None] | None = None) str | int | float | bool | list[JSONValue] | dict[str, JSONValue] | None¶
Construct request object and returns json response.
Исключения¶
- exception wlc.WeblateException(message: str | None = None)¶
Generic error.
- exception wlc.WeblatePermissionError(message: str | None = None)¶
You don’t have permission to access this object.
- exception wlc.WeblateDeniedError(message: str | None = None)¶
Access denied, API key is wrong or missing.
- exception wlc.WeblateThrottlingError(*, limit: str, retry_after: str)¶
Throttling on the server.
Объекты API¶
Объекты API поддерживают доступ к своим полям через атрибуты и ключи, а также keys() и items(). Доступ к известному полю, которое ещё не загружено, извлекает объект из API. get_data() возвращает копию только текущих загруженных данных без извлечения отсутствующих полей.
Объекты API наследуются от collections.UserDict. Они являются сопоставлениями, но isinstance(obj, dict) ложно. Проверки членства, get() и итерация используют текущие загруженные поля без извлечения отсутствующих полей. pop(), setdefault(), popitem() и clear() также работают только с загруженными полями без извлечения отсутствующих полей. Записи в сопоставление обновляют локальные данные объекта; они не отправляют изменения в API. Оператор | объединяет загруженные поля в новый обычный словарь, при этом значения из правого операнда имеют приоритет. Для потребителей, которым нужен обычный словарь, используйте obj.get_data() для загруженных полей или dict(obj.items()), чтобы включить все доступные поля, извлекая отсутствующие по мере необходимости. Стандартный json.dumps не сериализует объекты API напрямую; сначала преобразуйте их и любые вложенные объекты API в словари.
Проекты, компоненты и переводы имеют общие операции с репозиторием: repository(), commit(), push(), pull(), reset() и cleanup().
- class wlc.Project(weblate: Weblate, url: str, **kwargs: object)¶
Project object returned by the Weblate API.
- cleanup() dict[str, Any]¶
Cleanup Weblate repository from untracked files.
- commit() dict[str, Any]¶
Commit Weblate changes.
- create_component(*, params: RequestParams | None = None, **kwargs: object) dict[str, Any]¶
Create a new component in the project.
- delete() None¶
Delete the project.
- full_slug() str¶
Return the project slug.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- languages() builtins.list[LanguageStats]¶
Return language statistics for the project.
- pull() dict[str, Any]¶
Pull upstream changes into Weblate.
- push() dict[str, Any]¶
Push Weblate changes upstream.
- repository() LazyObject¶
Return repository object.
- reset() dict[str, Any]¶
Reset Weblate repository to upstream.
- statistics() Statistics¶
Return statistics for the project.
- class wlc.Component(weblate: Weblate, url: str, **kwargs: object)¶
Component object returned by the Weblate API.
- add_source_string(*, msgid: str, msgstr: str | builtins.list[str]) dict[str, Any]¶
Add a source string to a monolingual base file.
- add_translation(language: str) dict[str, Any]¶
Create a new translation in the component.
- cleanup() dict[str, Any]¶
Cleanup Weblate repository from untracked files.
- commit() dict[str, Any]¶
Commit Weblate changes.
- delete() None¶
Delete the component.
- download(*, convert: str | None = None) bytes¶
Download translation file from server.
- full_slug() str¶
Return the component slug including project and category path.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- list() Iterator[Translation]¶
List translations in the component.
- lock() dict[str, Any]¶
Lock component from translations.
- lock_status() dict[str, Any]¶
Return component lock status.
- patch(**kwargs: object) bytes¶
Update component fields.
- pull() dict[str, Any]¶
Pull upstream changes into Weblate.
- push() dict[str, Any]¶
Push Weblate changes upstream.
- repository() LazyObject¶
Return repository object.
- reset() dict[str, Any]¶
Reset Weblate repository to upstream.
- statistics() Iterator[TranslationStatistics]¶
Return statistics for component.
- unlock() dict[str, Any]¶
Unlock component from translations.
- class wlc.Translation(weblate: Weblate, url: str, **kwargs: object)¶
Translation object returned by the Weblate API.
- cleanup() dict[str, Any]¶
Cleanup Weblate repository from untracked files.
- commit() dict[str, Any]¶
Commit Weblate changes.
- delete() None¶
Delete the translation.
- download(*, convert: str | None = None) bytes¶
Download translation file from server.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- list() Translation¶
Load and return this object for API compatibility.
- pull() dict[str, Any]¶
Pull upstream changes into Weblate.
- push() dict[str, Any]¶
Push Weblate changes upstream.
- repository() LazyObject¶
Return repository object.
- reset() dict[str, Any]¶
Reset Weblate repository to upstream.
- statistics() TranslationStatistics¶
Return statistics for translation.
- upload(file: bytes | str | BinaryIO | TextIO, *, overwrite: bool | None = None, format: str | None = None, **kwargs: object) dict[str, Any]¶
Upload a translation file to server.
- class wlc.Unit(weblate: Weblate, url: str, **kwargs: object)¶
Translation unit object returned by the Weblate API.
- delete() bytes¶
Delete the unit.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- patch(**kwargs: object) bytes¶
Update unit fields using HTTP PATCH.
- put(**kwargs: object) bytes¶
Update unit fields using HTTP PUT.
- class wlc.Category(weblate: Weblate, url: str, **kwargs: object)¶
Category object returned by the Weblate API.
- full_slug() str¶
Return the category slug including the project and parent categories.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- class wlc.Language(weblate: Weblate, url: str, **kwargs: object)¶
Language object returned by the Weblate API.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- class wlc.Change(weblate: Weblate, url: str, **kwargs: object)¶
Change object returned by the Weblate API.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- class wlc.Statistics(weblate: Weblate, url: str = '', **kwargs: object)¶
Statistics object returned by the Weblate API.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- keys() Iterator[str]¶
Return present statistics fields without fetching URL-less objects.
- refresh() None¶
Refresh statistics when a backing API URL is available.
- class wlc.LanguageStats(weblate: Weblate, url: str = '', **kwargs: object)¶
Language statistics object returned by the Weblate API.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- keys() Iterator[str]¶
Return present statistics fields without fetching URL-less objects.
- refresh() None¶
Refresh statistics when a backing API URL is available.
- class wlc.TranslationStatistics(weblate: Weblate, url: str = '', **kwargs: object)¶
Translation statistics object returned by the Weblate API.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- keys() Iterator[str]¶
Return present statistics fields without fetching URL-less objects.
- refresh() None¶
Refresh statistics when a backing API URL is available.
- class wlc.ProjectRepository(weblate: Weblate, url: str, **kwargs: object)¶
Project repository status object.
- cleanup() dict[str, Any]¶
Cleanup Weblate repository from untracked files.
- commit() dict[str, Any]¶
Commit Weblate changes.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- pull() dict[str, Any]¶
Pull upstream changes into Weblate.
- push() dict[str, Any]¶
Push Weblate changes upstream.
- reset() dict[str, Any]¶
Reset Weblate repository to upstream.
- class wlc.Repository(weblate: Weblate, url: str, **kwargs: object)¶
Component or translation repository status object.
- cleanup() dict[str, Any]¶
Cleanup Weblate repository from untracked files.
- commit() dict[str, Any]¶
Commit Weblate changes.
- get_data() dict[str, Any]¶
Return a copy of the currently loaded object data.
- pull() dict[str, Any]¶
Pull upstream changes into Weblate.
- push() dict[str, Any]¶
Push Weblate changes upstream.
- reset() dict[str, Any]¶
Reset Weblate repository to upstream.
Activity¶
- class wlc.Activity(daily_activity: list[int], projects: list[Statistics])¶
Global daily activity and recently active project statistics.
client.get_activity() возвращает wlc.Activity с daily_activity (список ежедневных счётчиков) и projects (список объектов wlc.Statistics). Метки времени проекта разбираются как объекты datetime. Для этого требуется сервер, предоставляющий GET /api/activity/.
wlc.config¶
- exception wlc.config.WLCConfigurationError¶
Configuration could not be loaded or combines unsafe option sources.
- class wlc.config.WeblateConfig(section: str = 'weblate')¶
Configuration parser wrapper with defaults.
- Параметры:
section – Configuration section to use.
The parser loads user configuration, optional project configuration, and command-line or environment overrides. API keys in project configuration are constrained so unscoped secrets can not be paired with a project-provided API URL.
- static find_config() Path | None¶
Return the first user configuration file as a Path, or None.
- static find_project_config() Path | None¶
Return the nearest project configuration file as a Path, or None.
- get_allow_insecure_http() bool¶
Return whether authenticated non-local HTTP URLs are allowed.
The insecure HTTP opt-in is enable-only. Persistent configuration is scoped to the selected network origin.
- get_allow_insecure_ssl() bool¶
Return whether TLS verification is disabled for the selected origin.
- get_request_options() tuple[int, list[int] | None, list[str], float, int]¶
Get request retry and timeout options.
- get_url_key() tuple[str, str]¶
Get the resolved API URL and API key.
- load(path: Path | str | None = None) None¶
Load configuration from an explicit path or discovered locations.
When
pathis specified, only that file is loaded. Otherwise the user configuration is loaded first, followed by the nearest project configuration file from the current directory or its parents.
- validate_url_key() None¶
Validate URL and key source combination.
When the API URL comes from automatically discovered project configuration, unscoped keys must pin the destination explicitly:
WLC_KEYrequiresWLC_URL, and a command-line key requires a command-line URL.