El API de Python de Weblate

Instalación

El API de Python se envía separadamente como el paquete Cliente Weblate:

pip install wlc

wlc

El módulo wlc expone el cliente del API de Weblate, los objetos del API devueltos por el cliente y las excepciones que se generan para los fallos comunes del API.

Weblate

La clase Weblate es el punto de entrada principal de la API. Su construcción directa no carga los archivos de configuración del cliente Weblate ni las variables de entorno WLC_*; su configuración de conexión proviene de los argumentos proporcionados:

from wlc import Weblate

client = Weblate(
    url="https://hosted.weblate.org/api/",
    key="APIKEY",
)
projects = list(client.list_projects())

Para utilizar el archivo de configuración y la detección del entorno, cargue explícitamente WeblateConfig y páselo al cliente:

from wlc import Weblate
from wlc.config import WeblateConfig

config = WeblateConfig()
config.load()
client = Weblate(config=config)

Para seleccionar explícitamente la configuración del proyecto conservando la configuración personal y las credenciales con ámbito de URL, utilice config.load(project_path="/shared/weblate.ini"). Esto omite las comprobaciones automáticas de ubicación de detección, preservando las restricciones de transporte y credenciales del proyecto. No se puede combinar con una ruta de configuración completa explícita, como config.load("/trusted/weblate.ini"). Al construir WeblateConfig sin llamar a load(), se omiten los archivos de configuración, permitiendo al mismo tiempo la configuración del entorno cuando se pasa a Weblate.

El cliente Python sigue la misma política de URL, credenciales y transporte que el cliente de línea de comandos; consulte Security model. Los usuarios directos de la API siguen siendo responsables de renderizar y almacenar de forma segura los valores devueltos.

Las opciones de solicitud se validan al construir el cliente. retries debe ser un entero no negativo, timeout finito y mayor que cero, y backoff_factor finito y no negativo. status_forcelist solo acepta códigos de estado HTTP enteros de 400 a 599. Los argumentos directos no válidos generan WeblateException; los valores de configuración no válidos generan WLCConfigurationError, antes de que se envíe cualquier solicitud HTTP.

Las operaciones del repositorio, las cargas y la creación de traducciones, y la eliminación de componentes y traducciones esperan a completarse cuando Weblate devuelve una URL de tarea con HTTP 202. Los métodos de alto nivel devuelven el resultado habitual de la operación. Para una tarea enviada a través de una solicitud de bajo nivel, pase su URL a Weblate.wait_for_task() para obtener el resultado sin procesar de la tarea completada. El cliente espera hasta 1800 segundos (30 minutos) de forma predeterminada. Establezca task_timeout en la sección de configuración activa o anúlela al construir el cliente, por ejemplo Weblate(config=config, task_timeout=3600). Para una sola espera, use client.wait_for_task(task_url, timeout=60). Cada opción acepta segundos enteros, con cero para permitir una espera ilimitada.

Estos métodos de alto nivel envían sus solicitudes a través de Weblate.invoke_request() para poder inspeccionar el estado HTTP. Si su subclase intercepta operaciones de repositorio, creación o carga de traducciones, o eliminación de componentes o traducciones a través de post(), request() o raw_request(), mueva esa intercepción a invoke_request() y devuelva un requests.Response.

Cuando vence el plazo, WeblateTaskTimeoutError expone la URL de la tarea como task_url, para que pueda reanudar la espera. Una consulta que ya esté en curso, incluyendo sus reintentos HTTP, puede finalizar después del plazo y devolver un resultado completado. El tiempo de espera de la solicitud HTTP sigue aplicándose a cada solicitud. La caducidad y la interrupción dejan la tarea ejecutándose en el servidor.

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, task_timeout: int | None = None, allow_insecure_http: bool = False, allow_insecure_ssl: bool = False)

Weblate API wrapper object.

Parámetros:
  • 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.

  • task_timeout – Task wait in seconds, overriding configuration. Zero allows unlimited waiting.

  • 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 set allow_insecure_http only 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_activity() → Activity

Fetch daily activity and up to ten recently active projects.

get_component(path: str) → Component

Return component of given path.

get_object(path: str) → Project | Component | Translation | Unit

Return object based on path.

Operates on (project, component or translation objects.

get_project(path: str) → Project

Return project of given path.

get_translation(path: str) → Translation

Return translation of given path.

get_unit(path: str) → Unit

Return unit 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_categories(path: str = 'categories/') → Iterator[Category]

List categories in the instance.

list_changes(path: str = 'changes/') → Iterator[Change]

List changes in the instance.

list_components(path: str = 'components/') → Iterator[Component]

List components in the instance.

list_languages() → Iterator[Language]

List languages in the instance.

list_projects(path: str = 'projects/') → Iterator[Project]

List projects in the instance.

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.

wait_for_task(task_url: str, *, timeout: int | None = None) → str | int | float | bool | list[JSONValue] | dict[str, JSONValue] | None

Poll a task until completion and return its operation-specific result.

Excepciones

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.WeblateTaskTimeoutError(task_url: str)

The task polling deadline expired.

exception wlc.WeblateThrottlingError(*, limit: str, retry_after: str)

Throttling on the server.

Objetos de API

Los objetos de la API admiten el acceso a sus campos mediante atributos y claves, junto con keys() e items(). Al acceder a un campo conocido que aún no se ha cargado, se obtiene el objeto de la API. get_data() devuelve una copia únicamente de los datos cargados actualmente, sin obtener los campos que faltan.

Los objetos de la API heredan de collections.UserDict. Son asignaciones, pero isinstance(obj, dict) es falso. Las pruebas de pertenencia, get() y la iteración usan los campos cargados actualmente sin obtener los campos faltantes. pop(), setdefault(), popitem() y clear() también operan solo en campos cargados sin obtener los campos faltantes. Las escrituras de asignación actualizan los datos locales del objeto; no envían cambios a la API. El operador | fusiona los campos cargados en un nuevo diccionario simple, con los valores del operando derecho tomando precedencia. Para los consumidores que requieren un diccionario simple, use obj.get_data() para campos cargados o dict(obj.items()) para incluir todos los campos expuestos, obteniendo los campos faltantes según sea necesario. El json.dumps estándar no serializa los objetos de la API directamente; primero conviértalos y cualquier objeto de API anidado a diccionarios.

Los proyectos, componentes y traducciones comparten operaciones de repositorio: repository(), commit(), push(), pull(), reset() y cleanup().

class wlc.Project(weblate: Weblate, url: str, **kwargs: object)

Project object returned by the Weblate API.

categories() → Iterator[Category]

List categories in the project.

changes() → Iterator[Change]

List changes in the project.

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.

list() → Iterator[Component]

List components in 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.

changes() → Iterator[Change]

List changes 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.

changes() → Iterator[Change]

List changes in the translation.

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.

units(**kwargs: QueryValue) → Iterator[Unit]

List units in the 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.

list() → Unit

Load and return this object for API compatibility.

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() devuelve un objeto wlc.Activity con daily_activity (una lista de recuentos diarios) y projects (una lista de objetos wlc.Statistics). Las marcas de tiempo de los proyectos se analizan como fechas y horas. Esto requiere un servidor que proporcione 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.

Parámetros:

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.

classmethod find_project_config() → Path | None

Find the nearest configuration within repository and trust boundaries.

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 validated 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, *, project_path: Path | str | None = None) → None

Load configuration from an explicit path or discovered locations.

When path is specified, only that file is loaded. Otherwise the user configuration is loaded first, followed by the nearest project configuration file within discovery boundaries. project_path selects a project file explicitly while retaining user configuration and project restrictions. It cannot be combined with path.

validate_url_key() → None

Validate URL and key source combination.

When the API URL comes from project configuration, unscoped keys must pin the destination explicitly: WLC_KEY requires WLC_URL, and a command-line key requires a command-line URL.