easypaperless
easypaperless — Python API wrapper for paperless-ngx.
1"""easypaperless — Python API wrapper for paperless-ngx.""" 2 3import importlib.metadata 4import logging 5 6__version__: str = importlib.metadata.version("easypaperless") 7 8from easypaperless import resources as resources # noqa: F401 9from easypaperless._internal.sentinel import UNSET, Unset 10from easypaperless.client import PaperlessClient 11from easypaperless.exceptions import ( 12 AuthenticationError, 13 AuthError, 14 BadRequestError, 15 NotFoundError, 16 NotPaperlessError, 17 PaperlessError, 18 PermissionDeniedError, 19 RetryExhaustedError, 20 ServerError, 21 ServerResponseError, 22 TaskTimeoutError, 23 TransportError, 24 TransportTimeoutError, 25 UploadError, 26 ValidationError, 27) 28from easypaperless.models import ( 29 AuditLogActor, 30 AuditLogEntry, 31 Correspondent, 32 CustomField, 33 CustomFieldValue, 34 Document, 35 DocumentMetadata, 36 DocumentNote, 37 DocumentType, 38 FieldDataType, 39 FileMetadataEntry, 40 Group, 41 MatchingAlgorithm, 42 PagedResult, 43 PaperlessPermission, 44 PermissionSet, 45 SearchHit, 46 SetPermissions, 47 StoragePath, 48 SystemStatus, 49 SystemStatusDatabase, 50 SystemStatusMigrations, 51 SystemStatusStorage, 52 SystemStatusTasks, 53 Tag, 54 Task, 55 TaskStatus, 56 UiSettings, 57 UiSettingsServerSettings, 58 UiSettingsUser, 59 User, 60) 61from easypaperless.sync import SyncPaperlessClient 62 63logging.getLogger("easypaperless").addHandler(logging.NullHandler()) 64 65__all__ = [ 66 "__version__", 67 # Clients 68 "PaperlessClient", 69 "SyncPaperlessClient", 70 # Sentinel 71 "UNSET", 72 "Unset", 73 # Models 74 "MatchingAlgorithm", 75 "PagedResult", 76 "AuditLogActor", 77 "AuditLogEntry", 78 "Correspondent", 79 "CustomField", 80 "CustomFieldValue", 81 "Document", 82 "DocumentMetadata", 83 "DocumentNote", 84 "DocumentType", 85 "FieldDataType", 86 "FileMetadataEntry", 87 "Group", 88 "PermissionSet", 89 "SearchHit", 90 "SetPermissions", 91 "StoragePath", 92 "SystemStatus", 93 "SystemStatusDatabase", 94 "SystemStatusMigrations", 95 "SystemStatusStorage", 96 "SystemStatusTasks", 97 "Tag", 98 "Task", 99 "TaskStatus", 100 "UiSettings", 101 "UiSettingsServerSettings", 102 "UiSettingsUser", 103 "User", 104 "PaperlessPermission", 105 # Exceptions 106 "PaperlessError", 107 "AuthError", 108 "AuthenticationError", 109 "PermissionDeniedError", 110 "BadRequestError", 111 "NotFoundError", 112 "NotPaperlessError", 113 "ValidationError", 114 "ServerError", 115 "ServerResponseError", 116 "TransportError", 117 "TransportTimeoutError", 118 "UploadError", 119 "TaskTimeoutError", 120 "RetryExhaustedError", 121]
207class PaperlessClient(_ClientCore): 208 """Async client for the paperless-ngx API. 209 210 Resources are accessible as attributes: 211 212 * ``client.correspondents`` — correspondent CRUD + bulk ops - 213 see `easypaperless.resources.CorrespondentsResource` 214 * ``client.custom_fields`` — custom field CRUD - 215 see `easypaperless.resources.CustomFieldsResource` 216 * ``client.document_types`` — document type CRUD + bulk ops - 217 see `easypaperless.resources.DocumentTypesResource` 218 * ``client.documents`` — document CRUD, bulk ops, upload, download, history - 219 see `easypaperless.resources.DocumentsResource` 220 * ``client.documents.notes`` — document notes - 221 see `easypaperless.resources.NotesResource` 222 * ``client.storage_paths`` — storage path CRUD + bulk ops - 223 see `easypaperless.resources.StoragePathsResource` 224 * ``client.tags`` — tag CRUD + bulk ops - 225 see `easypaperless.resources.TagsResource` 226 * ``client.groups`` — group CRUD - 227 see `easypaperless.resources.GroupsResource` 228 * ``client.users`` — user CRUD - 229 see `easypaperless.resources.UsersResource` 230 * ``client.trash`` — list, restore, and permanently delete trashed documents - 231 see `easypaperless.resources.TrashResource` 232 * ``client.tasks`` — list, get, wait for, and acknowledge background tasks - 233 see `easypaperless.resources.TasksResource` 234 235 Server information is available directly on the client: 236 :meth:`server_version` (connection check), :meth:`system_status` and 237 :meth:`ui_settings` (current user and effective permissions). 238 239 Use as an async context manager to ensure the underlying HTTP connection 240 pool is closed when you are done: 241 242 Example: 243 async with PaperlessClient(url="http://localhost:8000", api_token="abc") as client: 244 docs = await client.documents.list(max_results=10) 245 """ 246 247 def __init__( 248 self, 249 url: str, 250 api_token: str, 251 *, 252 timeout: float = 30.0, 253 poll_interval: float = 2.0, 254 poll_timeout: float = 60.0, 255 retry_attempts: int = 0, 256 retry_backoff: float = 1.0, 257 retry_on: tuple[type[Exception], ...] | None = None, 258 tenacity_retrying: Any = None, 259 transport: httpx.AsyncBaseTransport | None = None, 260 ) -> None: 261 """Create an async paperless-ngx client. 262 263 Args: 264 url: Base URL of the paperless-ngx instance 265 (e.g. ``"http://localhost:8000"``). 266 api_token: API token. Generate one in paperless-ngx under 267 *Settings → API → Generate Token*. 268 timeout: Default request timeout in seconds. Default: ``30.0``. 269 poll_interval: Seconds between status checks when ``wait=True`` 270 is passed to :meth:`documents.upload`. Default: ``2.0``. 271 poll_timeout: Maximum seconds to wait for a document to finish 272 processing before raising 273 :exc:`~easypaperless.exceptions.TaskTimeoutError`. 274 Default: ``60.0``. 275 retry_attempts: Maximum number of retry attempts after the first 276 failure. ``0`` (the default) disables retrying entirely, 277 preserving backward-compatible behaviour. Requests that 278 create something are never retried: ``documents.upload()``, 279 every resource's ``create()`` and ``documents.notes.create()`` 280 send exactly one request and raise the error, because a retry 281 after a lost response could create a duplicate. 282 retry_backoff: Initial sleep in seconds between retry attempts; 283 doubles on each subsequent attempt. Default: ``1.0``. 284 retry_on: Tuple of exception types that trigger a retry. Defaults 285 to ``(ServerError, httpx.TimeoutException, httpx.ConnectError)``. 286 ``NotFoundError`` is intentionally excluded from the default set 287 so that genuine 404 responses are never silently retried. 288 Note: every ``httpx`` exception is converted inside the HTTP 289 layer before the retry loop sees it — timeouts become 290 :exc:`~easypaperless.exceptions.TransportTimeoutError`, all 291 other ``httpx`` errors (connection refused, DNS, TLS, protocol) 292 become :exc:`~easypaperless.exceptions.TransportError`; both are 293 ``ServerError`` subclasses. The ``httpx`` entries therefore 294 never match on their own: to retry only transport failures but 295 not 5xx responses, pass ``retry_on=(TransportError,)``; to 296 retry only 5xx responses, pass 297 ``retry_on=(ServerResponseError,)``. Retries apply to every 298 request path, including downloads and follow-up pages of 299 paginated lists, except the create requests listed under 300 ``retry_attempts``. 301 tenacity_retrying: An optional pre-configured 302 ``tenacity.AsyncRetrying`` instance. When supplied, the 303 ``retry_attempts``, ``retry_backoff``, and ``retry_on`` 304 parameters are ignored and tenacity drives the retry loop 305 instead. Requests that create something (``upload()``, 306 ``create()``, ``notes.create()``) bypass it and are never 307 retried, as with ``retry_attempts``. Must be ``AsyncRetrying`` — the sync 308 ``tenacity.Retrying`` is not compatible with the async HTTP 309 layer used internally. 310 transport: Optional ``httpx.AsyncBaseTransport`` passed to the 311 internal ``httpx.AsyncClient`` — e.g. an ``httpx.MockTransport`` 312 for tests, or an ``httpx.AsyncHTTPTransport`` with custom proxy, 313 local address or TLS settings. easypaperless still sets the 314 ``Authorization`` header, base URL, timeout, redirect handling 315 and retries. Default: ``None`` (httpx's default transport). 316 317 Example: 318 Testing with a mock transport:: 319 320 def handler(request: httpx.Request) -> httpx.Response: 321 return httpx.Response(200, json={"count": 0, "next": None, 322 "previous": None, "results": []}) 323 324 client = PaperlessClient(url="http://paperless.test", api_token="t", 325 transport=httpx.MockTransport(handler)) 326 """ 327 super().__init__( 328 url, 329 api_token, 330 timeout=timeout, 331 poll_interval=poll_interval, 332 poll_timeout=poll_timeout, 333 retry_attempts=retry_attempts, 334 retry_backoff=retry_backoff, 335 retry_on=retry_on, 336 tenacity_retrying=tenacity_retrying, 337 transport=transport, 338 ) 339 340 async def __aenter__(self) -> PaperlessClient: 341 return self 342 343 async def __aexit__(self, *args: Any) -> None: 344 await self.close() 345 346 async def server_version(self) -> str: 347 """Return the paperless-ngx version and verify URL and token. 348 349 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 350 response header. This is a cheap "test connection" call. 351 352 Returns: 353 The paperless-ngx version string, e.g. ``"2.18.4"``. 354 355 Raises: 356 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 357 to a paperless-ngx instance: the API root answered with 404, or 358 with a response (e.g. an HTML page, also after a redirect) that 359 lacks the ``X-Version`` header. 360 ~easypaperless.exceptions.AuthenticationError: The token was 361 refused (401). 362 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 363 permission (403). 364 ~easypaperless.exceptions.TransportError: The server could not be 365 reached (connection refused, DNS, TLS, timeout). 366 367 Example: 368 >>> version = await client.server_version() 369 >>> print(version) 370 2.18.4 371 """ 372 logger.info("Getting server version") 373 url = f"{self._session.base_url}/" 374 try: 375 # paperless-ngx redirects /api/ to its HTML schema view. Keep the 376 # httpx default "Accept: */*": with "Accept: application/json" the 377 # redirect target answers 406 Not Acceptable (verified in #0050). 378 resp = await self._session.get("/") 379 except NotFoundError as exc: 380 raise NotPaperlessError( 381 f"{url} does not appear to be a paperless-ngx instance: " 382 "the API root answered with 404 Not Found.", 383 status_code=exc.status_code, 384 ) from exc 385 version: str | None = resp.headers.get("X-Version") 386 if not version: 387 raise NotPaperlessError( 388 f"{url} does not appear to be a paperless-ngx instance: " 389 "the response carries no X-Version header.", 390 status_code=resp.status_code, 391 ) 392 return version 393 394 async def system_status(self) -> SystemStatus: 395 """Return paperless-ngx's system status (``GET /api/status/``). 396 397 Covers version, install type, server OS, storage, database, and the 398 health of Redis, Celery, the search index and the classifier. Every 399 field of the returned model is optional; fields a paperless version 400 does not send stay ``None``, unknown fields are ignored. 401 402 Returns: 403 A :class:`~easypaperless.models.system_status.SystemStatus`. 404 405 Raises: 406 ~easypaperless.exceptions.PermissionDeniedError: The token's user 407 is not an administrator (403). ``/api/status/`` requires a 408 staff or superuser account; paperless-ngx answers others with a 409 plain-text ``Insufficient permissions`` body, which becomes the 410 exception message. 411 ~easypaperless.exceptions.AuthenticationError: The token was 412 refused (401). 413 414 Example: 415 >>> status = await client.system_status() 416 >>> status.database.status 417 'OK' 418 """ 419 logger.info("Getting system status") 420 resp = await self._session.get("/status/") 421 return SystemStatus.model_validate(resp.json()) 422 423 async def ui_settings(self) -> UiSettings: 424 """Return the token user, their effective permissions and server settings. 425 426 Sends one authenticated ``GET /api/ui_settings/``. This is the only 427 paperless-ngx endpoint that reports the permissions the token's user 428 effectively has (granted directly and via groups), so it can tell a 429 service which permission is missing instead of an unexplained 403. 430 431 The endpoint itself requires the ``view_uisettings`` permission 432 (directly or via a group); superusers always have it. 433 434 Returns: 435 A :class:`~easypaperless.models.ui_settings.UiSettings` with 436 ``user``, ``permissions`` (bare codenames such as 437 ``"add_document"``) and ``settings``. Use 438 :meth:`~easypaperless.models.ui_settings.UiSettings.missing_permissions` 439 to compare against the permissions you need. 440 441 Raises: 442 ~easypaperless.exceptions.AuthenticationError: The token was 443 refused (401). 444 ~easypaperless.exceptions.PermissionDeniedError: The token's user 445 lacks the ``view_uisettings`` permission (403). 446 ~easypaperless.exceptions.TransportError: The server could not be 447 reached (connection refused, DNS, TLS, timeout). 448 449 Example: 450 >>> settings = await client.ui_settings() 451 >>> settings.missing_permissions({"add_document", "add_note"}) 452 {'add_note'} 453 """ 454 logger.info("Getting UI settings (current user and permissions)") 455 return await self._get_ui_settings()
Async client for the paperless-ngx API.
Resources are accessible as attributes:
client.correspondents— correspondent CRUD + bulk ops - seeeasypaperless.resources.CorrespondentsResourceclient.custom_fields— custom field CRUD - seeeasypaperless.resources.CustomFieldsResourceclient.document_types— document type CRUD + bulk ops - seeeasypaperless.resources.DocumentTypesResourceclient.documents— document CRUD, bulk ops, upload, download, history - seeeasypaperless.resources.DocumentsResourceclient.documents.notes— document notes - seeeasypaperless.resources.NotesResourceclient.storage_paths— storage path CRUD + bulk ops - seeeasypaperless.resources.StoragePathsResourceclient.tags— tag CRUD + bulk ops - seeeasypaperless.resources.TagsResourceclient.groups— group CRUD - seeeasypaperless.resources.GroupsResourceclient.users— user CRUD - seeeasypaperless.resources.UsersResourceclient.trash— list, restore, and permanently delete trashed documents - seeeasypaperless.resources.TrashResourceclient.tasks— list, get, wait for, and acknowledge background tasks - seeeasypaperless.resources.TasksResource
Server information is available directly on the client:
server_version() (connection check), system_status() and
ui_settings() (current user and effective permissions).
Use as an async context manager to ensure the underlying HTTP connection pool is closed when you are done:
Example:
async with PaperlessClient(url="http://localhost:8000", api_token="abc") as client: docs = await client.documents.list(max_results=10)
247 def __init__( 248 self, 249 url: str, 250 api_token: str, 251 *, 252 timeout: float = 30.0, 253 poll_interval: float = 2.0, 254 poll_timeout: float = 60.0, 255 retry_attempts: int = 0, 256 retry_backoff: float = 1.0, 257 retry_on: tuple[type[Exception], ...] | None = None, 258 tenacity_retrying: Any = None, 259 transport: httpx.AsyncBaseTransport | None = None, 260 ) -> None: 261 """Create an async paperless-ngx client. 262 263 Args: 264 url: Base URL of the paperless-ngx instance 265 (e.g. ``"http://localhost:8000"``). 266 api_token: API token. Generate one in paperless-ngx under 267 *Settings → API → Generate Token*. 268 timeout: Default request timeout in seconds. Default: ``30.0``. 269 poll_interval: Seconds between status checks when ``wait=True`` 270 is passed to :meth:`documents.upload`. Default: ``2.0``. 271 poll_timeout: Maximum seconds to wait for a document to finish 272 processing before raising 273 :exc:`~easypaperless.exceptions.TaskTimeoutError`. 274 Default: ``60.0``. 275 retry_attempts: Maximum number of retry attempts after the first 276 failure. ``0`` (the default) disables retrying entirely, 277 preserving backward-compatible behaviour. Requests that 278 create something are never retried: ``documents.upload()``, 279 every resource's ``create()`` and ``documents.notes.create()`` 280 send exactly one request and raise the error, because a retry 281 after a lost response could create a duplicate. 282 retry_backoff: Initial sleep in seconds between retry attempts; 283 doubles on each subsequent attempt. Default: ``1.0``. 284 retry_on: Tuple of exception types that trigger a retry. Defaults 285 to ``(ServerError, httpx.TimeoutException, httpx.ConnectError)``. 286 ``NotFoundError`` is intentionally excluded from the default set 287 so that genuine 404 responses are never silently retried. 288 Note: every ``httpx`` exception is converted inside the HTTP 289 layer before the retry loop sees it — timeouts become 290 :exc:`~easypaperless.exceptions.TransportTimeoutError`, all 291 other ``httpx`` errors (connection refused, DNS, TLS, protocol) 292 become :exc:`~easypaperless.exceptions.TransportError`; both are 293 ``ServerError`` subclasses. The ``httpx`` entries therefore 294 never match on their own: to retry only transport failures but 295 not 5xx responses, pass ``retry_on=(TransportError,)``; to 296 retry only 5xx responses, pass 297 ``retry_on=(ServerResponseError,)``. Retries apply to every 298 request path, including downloads and follow-up pages of 299 paginated lists, except the create requests listed under 300 ``retry_attempts``. 301 tenacity_retrying: An optional pre-configured 302 ``tenacity.AsyncRetrying`` instance. When supplied, the 303 ``retry_attempts``, ``retry_backoff``, and ``retry_on`` 304 parameters are ignored and tenacity drives the retry loop 305 instead. Requests that create something (``upload()``, 306 ``create()``, ``notes.create()``) bypass it and are never 307 retried, as with ``retry_attempts``. Must be ``AsyncRetrying`` — the sync 308 ``tenacity.Retrying`` is not compatible with the async HTTP 309 layer used internally. 310 transport: Optional ``httpx.AsyncBaseTransport`` passed to the 311 internal ``httpx.AsyncClient`` — e.g. an ``httpx.MockTransport`` 312 for tests, or an ``httpx.AsyncHTTPTransport`` with custom proxy, 313 local address or TLS settings. easypaperless still sets the 314 ``Authorization`` header, base URL, timeout, redirect handling 315 and retries. Default: ``None`` (httpx's default transport). 316 317 Example: 318 Testing with a mock transport:: 319 320 def handler(request: httpx.Request) -> httpx.Response: 321 return httpx.Response(200, json={"count": 0, "next": None, 322 "previous": None, "results": []}) 323 324 client = PaperlessClient(url="http://paperless.test", api_token="t", 325 transport=httpx.MockTransport(handler)) 326 """ 327 super().__init__( 328 url, 329 api_token, 330 timeout=timeout, 331 poll_interval=poll_interval, 332 poll_timeout=poll_timeout, 333 retry_attempts=retry_attempts, 334 retry_backoff=retry_backoff, 335 retry_on=retry_on, 336 tenacity_retrying=tenacity_retrying, 337 transport=transport, 338 )
Create an async paperless-ngx client.
Arguments:
- url: Base URL of the paperless-ngx instance
(e.g.
"http://localhost:8000"). - api_token: API token. Generate one in paperless-ngx under Settings → API → Generate Token.
- timeout: Default request timeout in seconds. Default:
30.0. - poll_interval: Seconds between status checks when
wait=Trueis passed todocuments.upload(). Default:2.0. - poll_timeout: Maximum seconds to wait for a document to finish
processing before raising
~easypaperless.exceptions.TaskTimeoutError. Default:60.0. - retry_attempts: Maximum number of retry attempts after the first
failure.
0(the default) disables retrying entirely, preserving backward-compatible behaviour. Requests that create something are never retried:documents.upload(), every resource'screate()anddocuments.notes.create()send exactly one request and raise the error, because a retry after a lost response could create a duplicate. - retry_backoff: Initial sleep in seconds between retry attempts;
doubles on each subsequent attempt. Default:
1.0. - retry_on: Tuple of exception types that trigger a retry. Defaults
to
(ServerError, httpx.TimeoutException, httpx.ConnectError).NotFoundErroris intentionally excluded from the default set so that genuine 404 responses are never silently retried. Note: everyhttpxexception is converted inside the HTTP layer before the retry loop sees it — timeouts become~easypaperless.exceptions.TransportTimeoutError, all otherhttpxerrors (connection refused, DNS, TLS, protocol) become~easypaperless.exceptions.TransportError; both areServerErrorsubclasses. Thehttpxentries therefore never match on their own: to retry only transport failures but not 5xx responses, passretry_on=(TransportError,); to retry only 5xx responses, passretry_on=(ServerResponseError,). Retries apply to every request path, including downloads and follow-up pages of paginated lists, except the create requests listed underretry_attempts. - tenacity_retrying: An optional pre-configured
tenacity.AsyncRetryinginstance. When supplied, theretry_attempts,retry_backoff, andretry_onparameters are ignored and tenacity drives the retry loop instead. Requests that create something (upload(),create(),notes.create()) bypass it and are never retried, as withretry_attempts. Must beAsyncRetrying— the synctenacity.Retryingis not compatible with the async HTTP layer used internally. - transport: Optional
httpx.AsyncBaseTransportpassed to the internalhttpx.AsyncClient— e.g. anhttpx.MockTransportfor tests, or anhttpx.AsyncHTTPTransportwith custom proxy, local address or TLS settings. easypaperless still sets theAuthorizationheader, base URL, timeout, redirect handling and retries. Default:None(httpx's default transport).
Example:
Testing with a mock transport::
def handler(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"count": 0, "next": None, "previous": None, "results": []}) client = PaperlessClient(url="http://paperless.test", api_token="t", transport=httpx.MockTransport(handler))
346 async def server_version(self) -> str: 347 """Return the paperless-ngx version and verify URL and token. 348 349 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 350 response header. This is a cheap "test connection" call. 351 352 Returns: 353 The paperless-ngx version string, e.g. ``"2.18.4"``. 354 355 Raises: 356 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 357 to a paperless-ngx instance: the API root answered with 404, or 358 with a response (e.g. an HTML page, also after a redirect) that 359 lacks the ``X-Version`` header. 360 ~easypaperless.exceptions.AuthenticationError: The token was 361 refused (401). 362 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 363 permission (403). 364 ~easypaperless.exceptions.TransportError: The server could not be 365 reached (connection refused, DNS, TLS, timeout). 366 367 Example: 368 >>> version = await client.server_version() 369 >>> print(version) 370 2.18.4 371 """ 372 logger.info("Getting server version") 373 url = f"{self._session.base_url}/" 374 try: 375 # paperless-ngx redirects /api/ to its HTML schema view. Keep the 376 # httpx default "Accept: */*": with "Accept: application/json" the 377 # redirect target answers 406 Not Acceptable (verified in #0050). 378 resp = await self._session.get("/") 379 except NotFoundError as exc: 380 raise NotPaperlessError( 381 f"{url} does not appear to be a paperless-ngx instance: " 382 "the API root answered with 404 Not Found.", 383 status_code=exc.status_code, 384 ) from exc 385 version: str | None = resp.headers.get("X-Version") 386 if not version: 387 raise NotPaperlessError( 388 f"{url} does not appear to be a paperless-ngx instance: " 389 "the response carries no X-Version header.", 390 status_code=resp.status_code, 391 ) 392 return version
Return the paperless-ngx version and verify URL and token.
Sends one authenticated GET /api/ and reads the X-Version
response header. This is a cheap "test connection" call.
Returns:
The paperless-ngx version string, e.g.
"2.18.4".
Raises:
- ~easypaperless.exceptions.NotPaperlessError: The URL does not point
to a paperless-ngx instance: the API root answered with 404, or
with a response (e.g. an HTML page, also after a redirect) that
lacks the
X-Versionheader. - ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
- ~easypaperless.exceptions.PermissionDeniedError: The token lacks permission (403).
- ~easypaperless.exceptions.TransportError: The server could not be reached (connection refused, DNS, TLS, timeout).
Example:
>>> version = await client.server_version() >>> print(version) 2.18.4
394 async def system_status(self) -> SystemStatus: 395 """Return paperless-ngx's system status (``GET /api/status/``). 396 397 Covers version, install type, server OS, storage, database, and the 398 health of Redis, Celery, the search index and the classifier. Every 399 field of the returned model is optional; fields a paperless version 400 does not send stay ``None``, unknown fields are ignored. 401 402 Returns: 403 A :class:`~easypaperless.models.system_status.SystemStatus`. 404 405 Raises: 406 ~easypaperless.exceptions.PermissionDeniedError: The token's user 407 is not an administrator (403). ``/api/status/`` requires a 408 staff or superuser account; paperless-ngx answers others with a 409 plain-text ``Insufficient permissions`` body, which becomes the 410 exception message. 411 ~easypaperless.exceptions.AuthenticationError: The token was 412 refused (401). 413 414 Example: 415 >>> status = await client.system_status() 416 >>> status.database.status 417 'OK' 418 """ 419 logger.info("Getting system status") 420 resp = await self._session.get("/status/") 421 return SystemStatus.model_validate(resp.json())
Return paperless-ngx's system status (GET /api/status/).
Covers version, install type, server OS, storage, database, and the
health of Redis, Celery, the search index and the classifier. Every
field of the returned model is optional; fields a paperless version
does not send stay None, unknown fields are ignored.
Returns:
Raises:
- ~easypaperless.exceptions.PermissionDeniedError: The token's user
is not an administrator (403).
/api/status/requires a staff or superuser account; paperless-ngx answers others with a plain-textInsufficient permissionsbody, which becomes the exception message. - ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
Example:
>>> status = await client.system_status() >>> status.database.status 'OK'
423 async def ui_settings(self) -> UiSettings: 424 """Return the token user, their effective permissions and server settings. 425 426 Sends one authenticated ``GET /api/ui_settings/``. This is the only 427 paperless-ngx endpoint that reports the permissions the token's user 428 effectively has (granted directly and via groups), so it can tell a 429 service which permission is missing instead of an unexplained 403. 430 431 The endpoint itself requires the ``view_uisettings`` permission 432 (directly or via a group); superusers always have it. 433 434 Returns: 435 A :class:`~easypaperless.models.ui_settings.UiSettings` with 436 ``user``, ``permissions`` (bare codenames such as 437 ``"add_document"``) and ``settings``. Use 438 :meth:`~easypaperless.models.ui_settings.UiSettings.missing_permissions` 439 to compare against the permissions you need. 440 441 Raises: 442 ~easypaperless.exceptions.AuthenticationError: The token was 443 refused (401). 444 ~easypaperless.exceptions.PermissionDeniedError: The token's user 445 lacks the ``view_uisettings`` permission (403). 446 ~easypaperless.exceptions.TransportError: The server could not be 447 reached (connection refused, DNS, TLS, timeout). 448 449 Example: 450 >>> settings = await client.ui_settings() 451 >>> settings.missing_permissions({"add_document", "add_note"}) 452 {'add_note'} 453 """ 454 logger.info("Getting UI settings (current user and permissions)") 455 return await self._get_ui_settings()
Return the token user, their effective permissions and server settings.
Sends one authenticated GET /api/ui_settings/. This is the only
paperless-ngx endpoint that reports the permissions the token's user
effectively has (granted directly and via groups), so it can tell a
service which permission is missing instead of an unexplained 403.
The endpoint itself requires the view_uisettings permission
(directly or via a group); superusers always have it.
Returns:
A
~easypaperless.models.ui_settings.UiSettingswithuser,permissions(bare codenames such as"add_document") andsettings. Use~easypaperless.models.ui_settings.UiSettings.missing_permissions()to compare against the permissions you need.
Raises:
- ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
- ~easypaperless.exceptions.PermissionDeniedError: The token's user
lacks the
view_uisettingspermission (403). - ~easypaperless.exceptions.TransportError: The server could not be reached (connection refused, DNS, TLS, timeout).
Example:
>>> settings = await client.ui_settings() >>> settings.missing_permissions({"add_document", "add_note"}) {'add_note'}
96class SyncPaperlessClient(_SyncCore): 97 """Synchronous interface to paperless-ngx. 98 99 Resources are accessible as attributes: 100 101 * ``client.correspondents`` — correspondent CRUD + bulk ops - 102 see `easypaperless.resources.SyncCorrespondentsResource` 103 * ``client.custom_fields`` — custom field CRUD - 104 see `easypaperless.resources.SyncCustomFieldsResource` 105 * ``client.document_types`` — document type CRUD + bulk ops - 106 see `easypaperless.resources.SyncDocumentTypesResource` 107 * ``client.documents`` — document CRUD, bulk ops, upload, download - 108 see `easypaperless.resources.SyncDocumentsResource` 109 * ``client.documents.notes`` — document notes - 110 see `easypaperless.resources.SyncNotesResource` 111 * ``client.storage_paths`` — storage path CRUD + bulk ops - 112 see `easypaperless.resources.SyncStoragePathsResource` 113 * ``client.tags`` — tag CRUD + bulk ops - 114 see `easypaperless.resources.SyncTagsResource` 115 * ``client.groups`` — group CRUD - 116 see `easypaperless.resources.SyncGroupsResource` 117 * ``client.users`` — user CRUD - 118 see `easypaperless.resources.SyncUsersResource` 119 * ``client.trash`` — list, restore, and permanently delete trashed documents - 120 see `easypaperless.resources.SyncTrashResource` 121 * ``client.tasks`` — list, get, wait for, and acknowledge background tasks - 122 see `easypaperless.resources.SyncTasksResource` 123 124 Server information is available directly on the client: 125 :meth:`server_version` (connection check), :meth:`system_status` and 126 :meth:`ui_settings` (current user and effective permissions). 127 128 All methods are synchronous wrappers around the async 129 :class:`~easypaperless.client.PaperlessClient`. Operations run on a 130 dedicated background event loop thread so that the httpx connection pool 131 is reused across calls and cleanup works correctly. 132 133 Use as a context manager to ensure proper cleanup: 134 135 Example: 136 with SyncPaperlessClient(url="http://localhost:8000", api_token="abc") as client: 137 tags = client.tags.list() 138 docs = client.documents.list(search="invoice") 139 140 Worker threads: 141 It is safe to construct and use a ``SyncPaperlessClient`` from a 142 worker thread while another event loop runs in the main thread (e.g. 143 a synchronous worker beside FastAPI/uvicorn, or via 144 ``asyncio.to_thread``). Each client owns its own private loop thread. 145 :meth:`close` (or leaving the ``with`` block) closes the connection 146 pool, stops that loop and joins its thread; calling it again is a 147 no-op. 148 149 Note: 150 Cannot be called directly from code running *inside* an event loop 151 (e.g. Jupyter notebooks or an ``async def`` body) — that would block 152 the loop. Use :class:`~easypaperless.client.PaperlessClient` there, 153 or move the sync calls into a worker thread. 154 """ 155 156 def __init__(self, url: str, api_token: str, **kwargs: Any) -> None: 157 """Create a synchronous paperless-ngx client. 158 159 Args: 160 url: Base URL of the paperless-ngx instance 161 (e.g. ``"http://localhost:8000"``). 162 api_token: API token. Generate one in paperless-ngx under 163 *Settings → API → Generate Token*. 164 **kwargs: Additional keyword arguments forwarded to 165 :class:`~easypaperless.client.PaperlessClient` (e.g. 166 ``poll_interval``, ``poll_timeout``, ``retry_attempts``, 167 ``retry_backoff``, ``retry_on``, ``tenacity_retrying``, 168 ``transport``). 169 When using ``tenacity_retrying``, pass a 170 ``tenacity.AsyncRetrying`` instance — the sync 171 ``tenacity.Retrying`` is not compatible because all requests 172 run on an internal async event loop. 173 174 ``retry_attempts`` / ``tenacity_retrying`` never apply to 175 requests that create something: ``documents.upload()``, every 176 resource's ``create()`` and ``documents.notes.create()`` send 177 exactly one request and raise the error, because a retry after 178 a lost response could create a duplicate. 179 180 ``transport`` (``httpx.AsyncBaseTransport | None``): custom or 181 mock transport for the internal ``httpx.AsyncClient``; must be 182 an *async* transport. An ``httpx.MockTransport`` works — its 183 handler is invoked on the client's internal loop thread. 184 Auth, base URL, timeout and retries stay under easypaperless's 185 control. 186 """ 187 super().__init__(url, api_token, **kwargs) 188 189 def __enter__(self) -> SyncPaperlessClient: 190 return self 191 192 def __exit__(self, *args: Any) -> None: 193 self.close() 194 195 def server_version(self) -> str: 196 """Return the paperless-ngx version and verify URL and token. 197 198 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 199 response header. This is a cheap "test connection" call. 200 201 Returns: 202 The paperless-ngx version string, e.g. ``"2.18.4"``. 203 204 Raises: 205 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 206 to a paperless-ngx instance: the API root answered with 404, or 207 with a response (e.g. an HTML page, also after a redirect) that 208 lacks the ``X-Version`` header. 209 ~easypaperless.exceptions.AuthenticationError: The token was 210 refused (401). 211 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 212 permission (403). 213 ~easypaperless.exceptions.TransportError: The server could not be 214 reached (connection refused, DNS, TLS, timeout). 215 216 Example: 217 >>> client.server_version() 218 '2.18.4' 219 """ 220 return self._run(self._async_client.server_version()) 221 222 def system_status(self) -> SystemStatus: 223 """Return paperless-ngx's system status (``GET /api/status/``). 224 225 Covers version, install type, server OS, storage, database, and the 226 health of Redis, Celery, the search index and the classifier. Every 227 field of the returned model is optional; fields a paperless version 228 does not send stay ``None``, unknown fields are ignored. 229 230 Returns: 231 A :class:`~easypaperless.models.system_status.SystemStatus`. 232 233 Raises: 234 ~easypaperless.exceptions.PermissionDeniedError: The token's user 235 is not an administrator (403). ``/api/status/`` requires a 236 staff or superuser account; paperless-ngx answers others with a 237 plain-text ``Insufficient permissions`` body, which becomes the 238 exception message. 239 ~easypaperless.exceptions.AuthenticationError: The token was 240 refused (401). 241 242 Example: 243 >>> client.system_status().database.status 244 'OK' 245 """ 246 return self._run(self._async_client.system_status()) 247 248 def ui_settings(self) -> UiSettings: 249 """Return the token user, their effective permissions and server settings. 250 251 Sends one authenticated ``GET /api/ui_settings/``. This is the only 252 paperless-ngx endpoint that reports the permissions the token's user 253 effectively has (granted directly and via groups), so it can tell a 254 service which permission is missing instead of an unexplained 403. 255 256 The endpoint itself requires the ``view_uisettings`` permission 257 (directly or via a group); superusers always have it. 258 259 Returns: 260 A :class:`~easypaperless.models.ui_settings.UiSettings` with 261 ``user``, ``permissions`` (bare codenames such as 262 ``"add_document"``) and ``settings``. Use 263 :meth:`~easypaperless.models.ui_settings.UiSettings.missing_permissions` 264 to compare against the permissions you need. 265 266 Raises: 267 ~easypaperless.exceptions.AuthenticationError: The token was 268 refused (401). 269 ~easypaperless.exceptions.PermissionDeniedError: The token's user 270 lacks the ``view_uisettings`` permission (403). 271 ~easypaperless.exceptions.TransportError: The server could not be 272 reached (connection refused, DNS, TLS, timeout). 273 274 Example: 275 >>> client.ui_settings().missing_permissions({"add_document", "add_note"}) 276 {'add_note'} 277 """ 278 return self._run(self._async_client.ui_settings())
Synchronous interface to paperless-ngx.
Resources are accessible as attributes:
client.correspondents— correspondent CRUD + bulk ops - seeeasypaperless.resources.SyncCorrespondentsResourceclient.custom_fields— custom field CRUD - seeeasypaperless.resources.SyncCustomFieldsResourceclient.document_types— document type CRUD + bulk ops - seeeasypaperless.resources.SyncDocumentTypesResourceclient.documents— document CRUD, bulk ops, upload, download - seeeasypaperless.resources.SyncDocumentsResourceclient.documents.notes— document notes - seeeasypaperless.resources.SyncNotesResourceclient.storage_paths— storage path CRUD + bulk ops - seeeasypaperless.resources.SyncStoragePathsResourceclient.tags— tag CRUD + bulk ops - seeeasypaperless.resources.SyncTagsResourceclient.groups— group CRUD - seeeasypaperless.resources.SyncGroupsResourceclient.users— user CRUD - seeeasypaperless.resources.SyncUsersResourceclient.trash— list, restore, and permanently delete trashed documents - seeeasypaperless.resources.SyncTrashResourceclient.tasks— list, get, wait for, and acknowledge background tasks - seeeasypaperless.resources.SyncTasksResource
Server information is available directly on the client:
server_version() (connection check), system_status() and
ui_settings() (current user and effective permissions).
All methods are synchronous wrappers around the async
~easypaperless.client.PaperlessClient. Operations run on a
dedicated background event loop thread so that the httpx connection pool
is reused across calls and cleanup works correctly.
Use as a context manager to ensure proper cleanup:
Example:
with SyncPaperlessClient(url="http://localhost:8000", api_token="abc") as client: tags = client.tags.list() docs = client.documents.list(search="invoice")
Worker threads:
It is safe to construct and use a
SyncPaperlessClientfrom a worker thread while another event loop runs in the main thread (e.g. a synchronous worker beside FastAPI/uvicorn, or viaasyncio.to_thread). Each client owns its own private loop thread.close()(or leaving thewithblock) closes the connection pool, stops that loop and joins its thread; calling it again is a no-op.
Note:
Cannot be called directly from code running inside an event loop (e.g. Jupyter notebooks or an
async defbody) — that would block the loop. Use~easypaperless.client.PaperlessClientthere, or move the sync calls into a worker thread.
156 def __init__(self, url: str, api_token: str, **kwargs: Any) -> None: 157 """Create a synchronous paperless-ngx client. 158 159 Args: 160 url: Base URL of the paperless-ngx instance 161 (e.g. ``"http://localhost:8000"``). 162 api_token: API token. Generate one in paperless-ngx under 163 *Settings → API → Generate Token*. 164 **kwargs: Additional keyword arguments forwarded to 165 :class:`~easypaperless.client.PaperlessClient` (e.g. 166 ``poll_interval``, ``poll_timeout``, ``retry_attempts``, 167 ``retry_backoff``, ``retry_on``, ``tenacity_retrying``, 168 ``transport``). 169 When using ``tenacity_retrying``, pass a 170 ``tenacity.AsyncRetrying`` instance — the sync 171 ``tenacity.Retrying`` is not compatible because all requests 172 run on an internal async event loop. 173 174 ``retry_attempts`` / ``tenacity_retrying`` never apply to 175 requests that create something: ``documents.upload()``, every 176 resource's ``create()`` and ``documents.notes.create()`` send 177 exactly one request and raise the error, because a retry after 178 a lost response could create a duplicate. 179 180 ``transport`` (``httpx.AsyncBaseTransport | None``): custom or 181 mock transport for the internal ``httpx.AsyncClient``; must be 182 an *async* transport. An ``httpx.MockTransport`` works — its 183 handler is invoked on the client's internal loop thread. 184 Auth, base URL, timeout and retries stay under easypaperless's 185 control. 186 """ 187 super().__init__(url, api_token, **kwargs)
Create a synchronous paperless-ngx client.
Arguments:
- url: Base URL of the paperless-ngx instance
(e.g.
"http://localhost:8000"). - api_token: API token. Generate one in paperless-ngx under Settings → API → Generate Token.
**kwargs: Additional keyword arguments forwarded to
~easypaperless.client.PaperlessClient(e.g.poll_interval,poll_timeout,retry_attempts,retry_backoff,retry_on,tenacity_retrying,transport). When usingtenacity_retrying, pass atenacity.AsyncRetryinginstance — the synctenacity.Retryingis not compatible because all requests run on an internal async event loop.retry_attempts/tenacity_retryingnever apply to requests that create something:documents.upload(), every resource'screate()anddocuments.notes.create()send exactly one request and raise the error, because a retry after a lost response could create a duplicate.transport(httpx.AsyncBaseTransport | None): custom or mock transport for the internalhttpx.AsyncClient; must be an async transport. Anhttpx.MockTransportworks — its handler is invoked on the client's internal loop thread. Auth, base URL, timeout and retries stay under easypaperless's control.
195 def server_version(self) -> str: 196 """Return the paperless-ngx version and verify URL and token. 197 198 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 199 response header. This is a cheap "test connection" call. 200 201 Returns: 202 The paperless-ngx version string, e.g. ``"2.18.4"``. 203 204 Raises: 205 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 206 to a paperless-ngx instance: the API root answered with 404, or 207 with a response (e.g. an HTML page, also after a redirect) that 208 lacks the ``X-Version`` header. 209 ~easypaperless.exceptions.AuthenticationError: The token was 210 refused (401). 211 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 212 permission (403). 213 ~easypaperless.exceptions.TransportError: The server could not be 214 reached (connection refused, DNS, TLS, timeout). 215 216 Example: 217 >>> client.server_version() 218 '2.18.4' 219 """ 220 return self._run(self._async_client.server_version())
Return the paperless-ngx version and verify URL and token.
Sends one authenticated GET /api/ and reads the X-Version
response header. This is a cheap "test connection" call.
Returns:
The paperless-ngx version string, e.g.
"2.18.4".
Raises:
- ~easypaperless.exceptions.NotPaperlessError: The URL does not point
to a paperless-ngx instance: the API root answered with 404, or
with a response (e.g. an HTML page, also after a redirect) that
lacks the
X-Versionheader. - ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
- ~easypaperless.exceptions.PermissionDeniedError: The token lacks permission (403).
- ~easypaperless.exceptions.TransportError: The server could not be reached (connection refused, DNS, TLS, timeout).
Example:
>>> client.server_version() '2.18.4'
222 def system_status(self) -> SystemStatus: 223 """Return paperless-ngx's system status (``GET /api/status/``). 224 225 Covers version, install type, server OS, storage, database, and the 226 health of Redis, Celery, the search index and the classifier. Every 227 field of the returned model is optional; fields a paperless version 228 does not send stay ``None``, unknown fields are ignored. 229 230 Returns: 231 A :class:`~easypaperless.models.system_status.SystemStatus`. 232 233 Raises: 234 ~easypaperless.exceptions.PermissionDeniedError: The token's user 235 is not an administrator (403). ``/api/status/`` requires a 236 staff or superuser account; paperless-ngx answers others with a 237 plain-text ``Insufficient permissions`` body, which becomes the 238 exception message. 239 ~easypaperless.exceptions.AuthenticationError: The token was 240 refused (401). 241 242 Example: 243 >>> client.system_status().database.status 244 'OK' 245 """ 246 return self._run(self._async_client.system_status())
Return paperless-ngx's system status (GET /api/status/).
Covers version, install type, server OS, storage, database, and the
health of Redis, Celery, the search index and the classifier. Every
field of the returned model is optional; fields a paperless version
does not send stay None, unknown fields are ignored.
Returns:
Raises:
- ~easypaperless.exceptions.PermissionDeniedError: The token's user
is not an administrator (403).
/api/status/requires a staff or superuser account; paperless-ngx answers others with a plain-textInsufficient permissionsbody, which becomes the exception message. - ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
Example:
>>> client.system_status().database.status 'OK'
248 def ui_settings(self) -> UiSettings: 249 """Return the token user, their effective permissions and server settings. 250 251 Sends one authenticated ``GET /api/ui_settings/``. This is the only 252 paperless-ngx endpoint that reports the permissions the token's user 253 effectively has (granted directly and via groups), so it can tell a 254 service which permission is missing instead of an unexplained 403. 255 256 The endpoint itself requires the ``view_uisettings`` permission 257 (directly or via a group); superusers always have it. 258 259 Returns: 260 A :class:`~easypaperless.models.ui_settings.UiSettings` with 261 ``user``, ``permissions`` (bare codenames such as 262 ``"add_document"``) and ``settings``. Use 263 :meth:`~easypaperless.models.ui_settings.UiSettings.missing_permissions` 264 to compare against the permissions you need. 265 266 Raises: 267 ~easypaperless.exceptions.AuthenticationError: The token was 268 refused (401). 269 ~easypaperless.exceptions.PermissionDeniedError: The token's user 270 lacks the ``view_uisettings`` permission (403). 271 ~easypaperless.exceptions.TransportError: The server could not be 272 reached (connection refused, DNS, TLS, timeout). 273 274 Example: 275 >>> client.ui_settings().missing_permissions({"add_document", "add_note"}) 276 {'add_note'} 277 """ 278 return self._run(self._async_client.ui_settings())
Return the token user, their effective permissions and server settings.
Sends one authenticated GET /api/ui_settings/. This is the only
paperless-ngx endpoint that reports the permissions the token's user
effectively has (granted directly and via groups), so it can tell a
service which permission is missing instead of an unexplained 403.
The endpoint itself requires the view_uisettings permission
(directly or via a group); superusers always have it.
Returns:
A
~easypaperless.models.ui_settings.UiSettingswithuser,permissions(bare codenames such as"add_document") andsettings. Use~easypaperless.models.ui_settings.UiSettings.missing_permissions()to compare against the permissions you need.
Raises:
- ~easypaperless.exceptions.AuthenticationError: The token was refused (401).
- ~easypaperless.exceptions.PermissionDeniedError: The token's user
lacks the
view_uisettingspermission (403). - ~easypaperless.exceptions.TransportError: The server could not be reached (connection refused, DNS, TLS, timeout).
Example:
>>> client.ui_settings().missing_permissions({"add_document", "add_note"}) {'add_note'}
9class Unset: 10 """Sentinel type signalling that a parameter was not provided. 11 12 Use the singleton :data:`UNSET` constant — do not instantiate directly. 13 """ 14 15 __slots__ = () 16 17 def __repr__(self) -> str: 18 return "UNSET"
Sentinel type signalling that a parameter was not provided.
Use the singleton UNSET constant — do not instantiate directly.
9class MatchingAlgorithm(IntEnum): 10 """Auto-matching algorithm used by tags, correspondents, document types, and storage paths.""" 11 12 NONE = 0 13 ANY_WORD = 1 14 ALL_WORDS = 2 15 EXACT = 3 16 REGEX = 4 17 FUZZY = 5 18 AUTO = 6
Auto-matching algorithm used by tags, correspondents, document types, and storage paths.
13class PagedResult(BaseModel, Generic[T]): 14 """Wrapper returned by all ``list()`` methods. 15 16 Holds the pagination metadata returned by paperless-ngx alongside the 17 deserialized resource items. 18 19 Attributes: 20 count: Total number of matching items as reported by the server on 21 the first fetched page. 22 next: URL of the next page as returned by the API, or ``None``. 23 Always ``None`` when auto-pagination is active (the default 24 ``page=None``), because the navigation URL is meaningless once 25 all pages have been consumed by the library. 26 previous: URL of the previous page as returned by the API, or 27 ``None``. Always ``None`` when auto-pagination is active. 28 all: All matching item IDs when the API includes them; ``None`` 29 otherwise. 30 results: The deserialized resource items for this page / all fetched 31 pages. 32 """ 33 34 count: int 35 next: str | None = None 36 previous: str | None = None 37 all: List[int] | None = None 38 results: List[T] = Field(default_factory=list)
Wrapper returned by all list() methods.
Holds the pagination metadata returned by paperless-ngx alongside the deserialized resource items.
Attributes:
- count: Total number of matching items as reported by the server on the first fetched page.
- next: URL of the next page as returned by the API, or
None. AlwaysNonewhen auto-pagination is active (the defaultpage=None), because the navigation URL is meaningless once all pages have been consumed by the library. - previous: URL of the previous page as returned by the API, or
None. AlwaysNonewhen auto-pagination is active. - all: All matching item IDs when the API includes them;
Noneotherwise. - results: The deserialized resource items for this page / all fetched pages.
51class AuditLogActor(BaseModel): 52 """The user who performed an audited action. 53 54 Attributes: 55 id: Numeric user ID. 56 username: Username of the actor. 57 """ 58 59 model_config = ConfigDict(extra="ignore") 60 61 id: int 62 username: str
The user who performed an audited action.
Attributes:
- id: Numeric user ID.
- username: Username of the actor.
65class AuditLogEntry(BaseModel): 66 """A single entry in a document's audit log. 67 68 Attributes: 69 id: Unique audit log entry ID. 70 timestamp: When the action occurred. 71 action: Action type (e.g. ``"create"``, ``"update"``). 72 changes: Free-form dict describing what changed. Keys and value 73 shapes vary by action type. 74 actor: The user who performed the action, or ``None`` for 75 system-generated entries. 76 """ 77 78 model_config = ConfigDict(extra="ignore") 79 80 id: int 81 timestamp: datetime 82 action: str 83 changes: dict[str, Any] 84 actor: AuditLogActor | None = None
A single entry in a document's audit log.
Attributes:
- id: Unique audit log entry ID.
- timestamp: When the action occurred.
- action: Action type (e.g.
"create","update"). - changes: Free-form dict describing what changed. Keys and value shapes vary by action type.
- actor: The user who performed the action, or
Nonefor system-generated entries.
14class Correspondent(BaseModel): 15 """A paperless-ngx correspondent (sender or recipient of a document). 16 17 Attributes: 18 id: Unique correspondent ID. 19 name: Correspondent name. 20 document_count: Number of documents assigned to this correspondent. 21 last_correspondence: Date of the most recent document assigned here, 22 or ``None``. 23 permissions: View/change permissions (user and group IDs). ``None`` 24 unless fetched with ``full_perms=True``. 25 """ 26 27 model_config = ConfigDict(extra="ignore") 28 29 id: int 30 name: str 31 slug: str | None = None 32 match: str | None = None 33 matching_algorithm: MatchingAlgorithm | None = None 34 is_insensitive: bool | None = None 35 document_count: int | None = None 36 last_correspondence: date | None = None 37 owner: int | None = None 38 user_can_change: bool | None = None 39 permissions: SetPermissions | None = None
A paperless-ngx correspondent (sender or recipient of a document).
Attributes:
- id: Unique correspondent ID.
- name: Correspondent name.
- document_count: Number of documents assigned to this correspondent.
- last_correspondence: Date of the most recent document assigned here,
or
None. - permissions: View/change permissions (user and group IDs).
Noneunless fetched withfull_perms=True.
26class CustomField(BaseModel): 27 """A custom field definition in paperless-ngx. 28 29 Attributes: 30 id: Unique custom-field ID. 31 name: Field name shown in the UI. 32 data_type: The value type for this field (see 33 :class:`FieldDataType`). 34 extra_data: Additional configuration (e.g. select options), or 35 ``None``. 36 document_count: Number of documents that have a value for this field. 37 """ 38 39 model_config = ConfigDict(extra="ignore") 40 41 id: int 42 name: str 43 data_type: FieldDataType 44 extra_data: Any = None 45 document_count: int | None = None
A custom field definition in paperless-ngx.
Attributes:
- id: Unique custom-field ID.
- name: Field name shown in the UI.
- data_type: The value type for this field (see
FieldDataType). - extra_data: Additional configuration (e.g. select options), or
None. - document_count: Number of documents that have a value for this field.
35class CustomFieldValue(BaseModel): 36 """A custom field value attached to a document. 37 38 Attributes: 39 field: ID of the :class:`~easypaperless.models.custom_fields.CustomField` 40 definition. 41 value: The stored value; its Python type depends on the field's 42 ``data_type``. 43 """ 44 45 model_config = ConfigDict(extra="ignore") 46 47 field: int 48 value: Any = None
A custom field value attached to a document.
Attributes:
- field: ID of the
~easypaperless.models.custom_fields.CustomFielddefinition. - value: The stored value; its Python type depends on the field's
data_type.
178class Document(BaseModel): 179 """A paperless-ngx document. 180 181 Attributes: 182 id: Unique document ID. 183 title: Document title. 184 content: Full OCR text content, if available. 185 tags: List of tag IDs assigned to this document. 186 document_type: ID of the assigned document type, or ``None``. 187 correspondent: ID of the assigned correspondent, or ``None``. 188 storage_path: ID of the assigned storage path, or ``None``. 189 created: Document creation date (``date`` object). Changed from 190 ``datetime`` to ``date`` in paperless-ngx API v9. 191 created_date: Date portion of creation. **Deprecated** by 192 paperless-ngx as of v9 — use ``created`` instead. Will be 193 removed in a future API version. 194 archive_serial_number: Archive serial number (ASN), or ``None``. 195 custom_fields: List of :class:`CustomFieldValue` instances. 196 notes: User notes attached to this document. 197 search_hit: Full-text search relevance metadata, populated only when 198 the document was returned by a full-text search. 199 metadata: Extended file-level metadata (checksums, sizes, MIME type). 200 ``None`` unless the document was fetched with 201 ``include_metadata=True`` or retrieved via 202 :meth:`~easypaperless._internal.resources.documents.DocumentsResource.get_metadata`. 203 permissions: View/change permissions (user and group IDs). ``None`` 204 unless the document was fetched with ``full_perms=True``. 205 """ 206 207 model_config = ConfigDict(extra="ignore", populate_by_name=True) 208 209 id: int 210 title: str 211 content: str | None = None 212 tags: list[int] = Field(default_factory=list) 213 document_type: int | None = None 214 correspondent: int | None = None 215 storage_path: int | None = None 216 created: date | None = None 217 created_date: date | None = None 218 modified: datetime | None = None 219 added: datetime | None = None 220 archive_serial_number: int | None = None 221 original_file_name: str | None = None 222 archived_file_name: str | None = None 223 owner: int | None = None 224 user_can_change: bool | None = None 225 is_shared_by_requester: bool | None = None 226 notes: list[DocumentNote] = Field(default_factory=list) 227 custom_fields: list[CustomFieldValue] = Field(default_factory=list) 228 search_hit: SearchHit | None = Field(default=None, alias="__search_hit__") 229 metadata: DocumentMetadata | None = None 230 permissions: SetPermissions | None = None
A paperless-ngx document.
Attributes:
- id: Unique document ID.
- title: Document title.
- content: Full OCR text content, if available.
- tags: List of tag IDs assigned to this document.
- document_type: ID of the assigned document type, or
None. - correspondent: ID of the assigned correspondent, or
None. - storage_path: ID of the assigned storage path, or
None. - created: Document creation date (
dateobject). Changed fromdatetimetodatein paperless-ngx API v9. - created_date: Date portion of creation. Deprecated by
paperless-ngx as of v9 — use
createdinstead. Will be removed in a future API version. - archive_serial_number: Archive serial number (ASN), or
None. - custom_fields: List of
CustomFieldValueinstances. - notes: User notes attached to this document.
- search_hit: Full-text search relevance metadata, populated only when the document was returned by a full-text search.
- metadata: Extended file-level metadata (checksums, sizes, MIME type).
Noneunless the document was fetched withinclude_metadata=Trueor retrieved via~easypaperless._internal.resources.documents.DocumentsResource.get_metadata(). - permissions: View/change permissions (user and group IDs).
Noneunless the document was fetched withfull_perms=True.
136class DocumentMetadata(BaseModel): 137 """Extended file-level metadata for a document. 138 139 Returned by ``GET /api/documents/{id}/metadata/`` and optionally attached 140 to a :class:`Document` when 141 :meth:`~easypaperless._internal.resources.documents.DocumentsResource.get` 142 is called with ``include_metadata=True``. 143 144 Because reading metadata requires disk I/O it is **not** included in 145 document list responses; it must be requested explicitly. 146 147 Attributes: 148 original_checksum: MD5 checksum of the original uploaded file. 149 original_size: Size of the original file in bytes. 150 original_mime_type: MIME type of the original file 151 (e.g. ``"application/pdf"``). 152 media_filename: Path of the archived file relative to the 153 paperless-ngx media root. 154 has_archive_version: ``True`` when paperless-ngx has produced an 155 archived (post-processed) PDF in addition to the original. 156 original_metadata: File-level metadata entries extracted from the 157 original document (PDF XMP/info tags, etc.). 158 archive_checksum: MD5 checksum of the archived file, or ``None`` if 159 no archive version exists. 160 archive_size: Size of the archived file in bytes, or ``None``. 161 archive_metadata: File-level metadata entries from the archived 162 document, or ``None``. 163 """ 164 165 model_config = ConfigDict(extra="ignore") 166 167 original_checksum: str | None = None 168 original_size: int | None = None 169 original_mime_type: str | None = None 170 media_filename: str | None = None 171 has_archive_version: bool | None = None 172 original_metadata: list[FileMetadataEntry] = Field(default_factory=list) 173 archive_checksum: str | None = None 174 archive_size: int | None = None 175 archive_metadata: list[FileMetadataEntry] | None = None
Extended file-level metadata for a document.
Returned by GET /api/documents/{id}/metadata/ and optionally attached
to a Document when
~easypaperless._internal.resources.documents.DocumentsResource.get()
is called with include_metadata=True.
Because reading metadata requires disk I/O it is not included in document list responses; it must be requested explicitly.
Attributes:
- original_checksum: MD5 checksum of the original uploaded file.
- original_size: Size of the original file in bytes.
- original_mime_type: MIME type of the original file
(e.g.
"application/pdf"). - media_filename: Path of the archived file relative to the paperless-ngx media root.
- has_archive_version:
Truewhen paperless-ngx has produced an archived (post-processed) PDF in addition to the original. - original_metadata: File-level metadata entries extracted from the original document (PDF XMP/info tags, etc.).
- archive_checksum: MD5 checksum of the archived file, or
Noneif no archive version exists. - archive_size: Size of the archived file in bytes, or
None. - archive_metadata: File-level metadata entries from the archived
document, or
None.
87class DocumentNote(BaseModel): 88 """A user note attached to a document. 89 90 Attributes: 91 id: Unique note ID. 92 note: Text content of the note. 93 created: Timestamp when the note was created. 94 document: ID of the parent document. 95 user: ID of the user who created the note. 96 """ 97 98 model_config = ConfigDict(extra="ignore") 99 100 id: int | None = None 101 note: str 102 created: datetime | None = None 103 document: int | None = None 104 user: int | None = None 105 106 @field_validator("user", mode="before") 107 @classmethod 108 def _coerce_user(cls, v: object) -> int | None: 109 if isinstance(v, dict): 110 return v.get("id") 111 return v # type: ignore[return-value]
A user note attached to a document.
Attributes:
- id: Unique note ID.
- note: Text content of the note.
- created: Timestamp when the note was created.
- document: ID of the parent document.
- user: ID of the user who created the note.
12class DocumentType(BaseModel): 13 """A paperless-ngx document type (e.g. Invoice, Receipt, Contract). 14 15 Attributes: 16 id: Unique document-type ID. 17 name: Document-type name. 18 document_count: Number of documents assigned to this document type. 19 permissions: View/change permissions (user and group IDs). ``None`` 20 unless fetched with ``full_perms=True``. 21 """ 22 23 model_config = ConfigDict(extra="ignore") 24 25 id: int 26 name: str 27 slug: str | None = None 28 match: str | None = None 29 matching_algorithm: MatchingAlgorithm | None = None 30 is_insensitive: bool | None = None 31 document_count: int | None = None 32 owner: int | None = None 33 user_can_change: bool | None = None 34 permissions: SetPermissions | None = None
A paperless-ngx document type (e.g. Invoice, Receipt, Contract).
Attributes:
- id: Unique document-type ID.
- name: Document-type name.
- document_count: Number of documents assigned to this document type.
- permissions: View/change permissions (user and group IDs).
Noneunless fetched withfull_perms=True.
12class FieldDataType(StrEnum): 13 """Allowed data types for a custom field.""" 14 15 string = "string" 16 boolean = "boolean" 17 integer = "integer" 18 float = "float" 19 monetary = "monetary" 20 date = "date" 21 url = "url" 22 documentlink = "documentlink" 23 select = "select"
Allowed data types for a custom field.
114class FileMetadataEntry(BaseModel): 115 """A single embedded metadata key-value pair from a document file. 116 117 Paperless-ngx reads file-level metadata (e.g. PDF XMP/info tags) and 118 exposes each entry in this format. ``namespace`` and ``prefix`` are 119 ``None`` for non-namespaced entries. 120 121 Attributes: 122 namespace: XML namespace URI, or ``None``. 123 prefix: Namespace prefix (e.g. ``"pdf"``), or ``None``. 124 key: Metadata key (e.g. ``"Producer"``). 125 value: Metadata value as a string. 126 """ 127 128 model_config = ConfigDict(extra="ignore") 129 130 namespace: str | None = None 131 prefix: str | None = None 132 key: str 133 value: str
A single embedded metadata key-value pair from a document file.
Paperless-ngx reads file-level metadata (e.g. PDF XMP/info tags) and
exposes each entry in this format. namespace and prefix are
None for non-namespaced entries.
Attributes:
- namespace: XML namespace URI, or
None. - prefix: Namespace prefix (e.g.
"pdf"), orNone. - key: Metadata key (e.g.
"Producer"). - value: Metadata value as a string.
9class Group(BaseModel): 10 """A paperless-ngx user group. 11 12 Groups bundle permissions and can be granted object permissions 13 (``set_permissions``) on documents and other resources. 14 15 Attributes: 16 id: Unique group ID (set by the API). 17 name: Group name. 18 permissions: Permission codenames granted to the group, without the 19 app label (e.g. ``"view_document"``), as paperless-ngx returns and 20 accepts them. :data:`~easypaperless.PaperlessPermission` holds the 21 app-labelled form (``"documents.view_document"``); strip the 22 prefix (``perm.split(".", 1)[1]``) before sending one here. 23 """ 24 25 model_config = ConfigDict(extra="ignore") 26 27 id: int 28 name: str 29 permissions: list[str] | None = None
A paperless-ngx user group.
Groups bundle permissions and can be granted object permissions
(set_permissions) on documents and other resources.
Attributes:
- id: Unique group ID (set by the API).
- name: Group name.
- permissions: Permission codenames granted to the group, without the
app label (e.g.
"view_document"), as paperless-ngx returns and accepts them.~easypaperless.PaperlessPermissionholds the app-labelled form ("documents.view_document"); strip the prefix (perm.split(".", 1)[1]) before sending one here.
7class PermissionSet(BaseModel): 8 users: list[int] = Field(default_factory=list) 9 groups: list[int] = Field(default_factory=list)
!!! abstract "Usage Documentation" Models
A base class for creating Pydantic models.
Attributes:
- __class_vars__: The names of the class variables defined on the model.
- __private_attributes__: Metadata about the private attributes of the model.
- __signature__: The synthesized
__init__[Signature][inspect.Signature] of the model. - __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
- __pydantic_core_schema__: The core schema of the model.
- __pydantic_custom_init__: Whether the model has a custom
__init__function. - __pydantic_decorators__: Metadata containing the decorators defined on the model.
This replaces
Model.__validators__andModel.__root_validators__from Pydantic V1. - __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
- __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
- __pydantic_post_init__: The name of the post-init method for the model, if defined.
- __pydantic_root_model__: Whether the model is a [
RootModel][pydantic.root_model.RootModel]. - __pydantic_serializer__: The
pydantic-coreSchemaSerializerused to dump instances of the model. - __pydantic_validator__: The
pydantic-coreSchemaValidatorused to validate instances of the model. - __pydantic_fields__: A dictionary of field names and their corresponding [
FieldInfo][pydantic.fields.FieldInfo] objects. - __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [
ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects. - __pydantic_extra__: A dictionary containing extra values, if [
extra][pydantic.config.ConfigDict.extra] is set to'allow'. - __pydantic_fields_set__: The names of fields explicitly set during instantiation.
- __pydantic_private__: Values of private attributes set on the model instance.
18class SearchHit(BaseModel): 19 """Full-text search relevance metadata returned alongside a document. 20 21 Attributes: 22 score: Relevance score assigned by the Whoosh FTS engine. 23 highlights: HTML snippet with matching terms highlighted. 24 rank: Position in the result set by relevance. 25 """ 26 27 model_config = ConfigDict(extra="ignore") 28 29 score: float | None = None 30 highlights: str | None = None 31 note_highlights: str | None = None 32 rank: int | None = None
Full-text search relevance metadata returned alongside a document.
Attributes:
- score: Relevance score assigned by the Whoosh FTS engine.
- highlights: HTML snippet with matching terms highlighted.
- rank: Position in the result set by relevance.
12class SetPermissions(BaseModel): 13 view: PermissionSet = Field(default_factory=PermissionSet) 14 change: PermissionSet = Field(default_factory=PermissionSet)
!!! abstract "Usage Documentation" Models
A base class for creating Pydantic models.
Attributes:
- __class_vars__: The names of the class variables defined on the model.
- __private_attributes__: Metadata about the private attributes of the model.
- __signature__: The synthesized
__init__[Signature][inspect.Signature] of the model. - __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
- __pydantic_core_schema__: The core schema of the model.
- __pydantic_custom_init__: Whether the model has a custom
__init__function. - __pydantic_decorators__: Metadata containing the decorators defined on the model.
This replaces
Model.__validators__andModel.__root_validators__from Pydantic V1. - __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
- __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
- __pydantic_post_init__: The name of the post-init method for the model, if defined.
- __pydantic_root_model__: Whether the model is a [
RootModel][pydantic.root_model.RootModel]. - __pydantic_serializer__: The
pydantic-coreSchemaSerializerused to dump instances of the model. - __pydantic_validator__: The
pydantic-coreSchemaValidatorused to validate instances of the model. - __pydantic_fields__: A dictionary of field names and their corresponding [
FieldInfo][pydantic.fields.FieldInfo] objects. - __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [
ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects. - __pydantic_extra__: A dictionary containing extra values, if [
extra][pydantic.config.ConfigDict.extra] is set to'allow'. - __pydantic_fields_set__: The names of fields explicitly set during instantiation.
- __pydantic_private__: Values of private attributes set on the model instance.
12class StoragePath(BaseModel): 13 """A paperless-ngx storage path — controls where archived files are stored. 14 15 Attributes: 16 id: Unique storage-path ID. 17 name: Storage-path name. 18 path: Template string used to build the storage path, e.g. 19 ``"{created_year}/{correspondent}/{title}"``. 20 document_count: Number of documents using this storage path. 21 permissions: View/change permissions (user and group IDs). ``None`` 22 unless fetched with ``full_perms=True``. 23 """ 24 25 model_config = ConfigDict(extra="ignore") 26 27 id: int 28 name: str 29 slug: str | None = None 30 path: str | None = None 31 match: str | None = None 32 matching_algorithm: MatchingAlgorithm | None = None 33 is_insensitive: bool | None = None 34 document_count: int | None = None 35 owner: int | None = None 36 user_can_change: bool | None = None 37 permissions: SetPermissions | None = None
A paperless-ngx storage path — controls where archived files are stored.
Attributes:
- id: Unique storage-path ID.
- name: Storage-path name.
- path: Template string used to build the storage path, e.g.
"{created_year}/{correspondent}/{title}". - document_count: Number of documents using this storage path.
- permissions: View/change permissions (user and group IDs).
Noneunless fetched withfull_perms=True.
105class SystemStatus(BaseModel): 106 """paperless-ngx system status, as returned by ``GET /api/status/``. 107 108 Returned by :meth:`~easypaperless.PaperlessClient.system_status`. 109 110 Attributes: 111 version: paperless-ngx version (paperless sends it as ``pngx_version``). 112 server_os: Operating system of the server. 113 install_type: How paperless-ngx is installed (e.g. ``"docker"``). 114 storage: Media storage disk space. 115 database: Database health and migrations. 116 tasks: Redis, Celery, search index, classifier and sanity check health. 117 """ 118 119 model_config = ConfigDict(extra="ignore", populate_by_name=True) 120 121 version: str | None = Field( 122 default=None, validation_alias=AliasChoices("pngx_version", "version") 123 ) 124 server_os: str | None = None 125 install_type: str | None = None 126 storage: SystemStatusStorage | None = None 127 database: SystemStatusDatabase | None = None 128 tasks: SystemStatusTasks | None = None
paperless-ngx system status, as returned by GET /api/status/.
Returned by ~easypaperless.PaperlessClient.system_status().
Attributes:
- version: paperless-ngx version (paperless sends it as
pngx_version). - server_os: Operating system of the server.
- install_type: How paperless-ngx is installed (e.g.
"docker"). - storage: Media storage disk space.
- database: Database health and migrations.
- tasks: Redis, Celery, search index, classifier and sanity check health.
45class SystemStatusDatabase(BaseModel): 46 """Database health. 47 48 Attributes: 49 type: Database engine (e.g. ``"postgresql"``, ``"sqlite"``). 50 url: Database name or URL as reported by paperless-ngx. 51 status: ``"OK"`` or ``"ERROR"``. 52 error: Error message when the status is not OK. 53 migration_status: Applied and unapplied migrations. 54 """ 55 56 model_config = ConfigDict(extra="ignore") 57 58 type: str | None = None 59 url: str | None = None 60 status: str | None = None 61 error: str | None = None 62 migration_status: SystemStatusMigrations | None = None
Database health.
Attributes:
- type: Database engine (e.g.
"postgresql","sqlite"). - url: Database name or URL as reported by paperless-ngx.
- status:
"OK"or"ERROR". - error: Error message when the status is not OK.
- migration_status: Applied and unapplied migrations.
31class SystemStatusMigrations(BaseModel): 32 """Database migration state. 33 34 Attributes: 35 latest_migration: Name of the most recently applied migration. 36 unapplied_migrations: Names of migrations not yet applied. 37 """ 38 39 model_config = ConfigDict(extra="ignore") 40 41 latest_migration: str | None = None 42 unapplied_migrations: list[str] | None = None
Database migration state.
Attributes:
- latest_migration: Name of the most recently applied migration.
- unapplied_migrations: Names of migrations not yet applied.
17class SystemStatusStorage(BaseModel): 18 """Disk space of the paperless-ngx media storage. 19 20 Attributes: 21 total: Total size of the storage in bytes. 22 available: Free space in bytes. 23 """ 24 25 model_config = ConfigDict(extra="ignore") 26 27 total: int | None = None 28 available: int | None = None
Disk space of the paperless-ngx media storage.
Attributes:
- total: Total size of the storage in bytes.
- available: Free space in bytes.
65class SystemStatusTasks(BaseModel): 66 """Health of the background services (Redis, Celery, index, classifier). 67 68 Attributes: 69 redis_url: Redis broker URL. 70 redis_status: Redis status. 71 redis_error: Redis error message, if any. 72 celery_status: Celery worker status. 73 celery_url: Name of the responding Celery worker. 74 celery_error: Celery error message, if any. 75 index_status: Search index status. 76 index_last_modified: When the search index was last modified. 77 index_error: Search index error message, if any. 78 classifier_status: Status of the automatic matching classifier. 79 classifier_last_trained: When the classifier was last trained. 80 classifier_error: Classifier error message, if any. 81 sanity_check_status: Status of the last sanity check. 82 sanity_check_last_run: When the sanity check last ran. 83 sanity_check_error: Sanity check error message, if any. 84 """ 85 86 model_config = ConfigDict(extra="ignore") 87 88 redis_url: str | None = None 89 redis_status: str | None = None 90 redis_error: str | None = None 91 celery_status: str | None = None 92 celery_url: str | None = None 93 celery_error: str | None = None 94 index_status: str | None = None 95 index_last_modified: datetime | None = None 96 index_error: str | None = None 97 classifier_status: str | None = None 98 classifier_last_trained: datetime | None = None 99 classifier_error: str | None = None 100 sanity_check_status: str | None = None 101 sanity_check_last_run: datetime | None = None 102 sanity_check_error: str | None = None
Health of the background services (Redis, Celery, index, classifier).
Attributes:
- redis_url: Redis broker URL.
- redis_status: Redis status.
- redis_error: Redis error message, if any.
- celery_status: Celery worker status.
- celery_url: Name of the responding Celery worker.
- celery_error: Celery error message, if any.
- index_status: Search index status.
- index_last_modified: When the search index was last modified.
- index_error: Search index error message, if any.
- classifier_status: Status of the automatic matching classifier.
- classifier_last_trained: When the classifier was last trained.
- classifier_error: Classifier error message, if any.
- sanity_check_status: Status of the last sanity check.
- sanity_check_last_run: When the sanity check last ran.
- sanity_check_error: Sanity check error message, if any.
12class Tag(BaseModel): 13 """A paperless-ngx tag. 14 15 Attributes: 16 id: Unique tag ID. 17 name: Tag name. 18 color: Hex colour code used in the UI (e.g. ``"#ff0000"``). 19 is_inbox_tag: If ``True``, newly ingested documents receive this tag 20 automatically until they are processed. 21 document_count: Number of documents currently assigned to this tag. 22 parent: ID of the parent tag for hierarchical tag trees, or ``None``. 23 children: IDs of child tags, or ``None``. 24 permissions: View/change permissions (user and group IDs). ``None`` 25 unless fetched with ``full_perms=True``. 26 """ 27 28 model_config = ConfigDict(extra="ignore") 29 30 id: int 31 name: str 32 slug: str | None = None 33 color: str | None = None 34 text_color: str | None = None 35 match: str | None = None 36 matching_algorithm: MatchingAlgorithm | None = None 37 is_insensitive: bool | None = None 38 is_inbox_tag: bool | None = None 39 document_count: int | None = None 40 owner: int | None = None 41 user_can_change: bool | None = None 42 permissions: SetPermissions | None = None 43 parent: int | None = None 44 children: list[int] | None = None
A paperless-ngx tag.
Attributes:
- id: Unique tag ID.
- name: Tag name.
- color: Hex colour code used in the UI (e.g.
"#ff0000"). - is_inbox_tag: If
True, newly ingested documents receive this tag automatically until they are processed. - document_count: Number of documents currently assigned to this tag.
- parent: ID of the parent tag for hierarchical tag trees, or
None. - children: IDs of child tags, or
None. - permissions: View/change permissions (user and group IDs).
Noneunless fetched withfull_perms=True.
25class Task(BaseModel): 26 """A paperless-ngx background task (e.g. document consumption). 27 28 Values are taken from paperless-ngx unaltered; unknown fields are ignored. 29 30 Attributes: 31 id: Numeric database ID of the task (used by 32 :meth:`~easypaperless.resources.TasksResource.acknowledge`). 33 task_id: Unique Celery task identifier (UUID string), as returned by 34 ``documents.upload(wait=False)``. 35 task_name: Name of the task, e.g. ``"consume_file"``. 36 task_file_name: Original file name submitted for processing. 37 type: Task type as reported by paperless-ngx: ``"auto_task"`` (e.g. 38 a document consumption), ``"scheduled_task"`` or ``"manual_task"``. 39 status: Current task status as a :class:`TaskStatus` enum value. A 40 status this library does not know yet is kept as the plain string 41 paperless-ngx sent (it compares equal to that string). 42 result: Result or error message exactly as paperless-ngx reports it. 43 Consumption failures start with ``"<task_file_name>: "``, e.g. 44 ``"Success. New document id 42 created"``, 45 ``"x.pdf: Not consuming x.pdf: It is a duplicate of y (#12)."`` 46 (a duplicate of a trashed document ends in 47 ``" Note: existing document is in the trash."``) or 48 ``"x.pdf: Error occurred while consuming document x.pdf: ..."``. 49 acknowledged: Whether the task was acknowledged (dismissed in the UI). 50 related_document: Document ID as a string, or ``None``. On 51 ``SUCCESS`` it is the new document. On a duplicate ``FAILURE`` it 52 is the *existing* document the upload duplicates (``None`` when 53 that document is in the trash). ``None`` for other failures. 54 date_created: When the task was created. 55 date_done: When the task finished, ``None`` while it is running. 56 owner: ID of the user owning the task, if any. 57 """ 58 59 model_config = ConfigDict(extra="ignore") 60 61 id: int | None = None 62 task_id: str 63 task_name: str | None = None 64 task_file_name: str | None = None 65 type: str | None = None 66 status: TaskStatus | str | None = None 67 result: str | None = None 68 acknowledged: bool | None = None 69 related_document: str | None = None 70 date_created: datetime | None = None 71 date_done: datetime | None = None 72 owner: int | None = None 73 74 @field_validator("status", mode="before") 75 @classmethod 76 def _known_status_as_enum(cls, value: Any) -> Any: 77 """Parse known statuses as :class:`TaskStatus`; keep unknown strings as-is.""" 78 if isinstance(value, str) and not isinstance(value, TaskStatus): 79 try: 80 return TaskStatus(value) 81 except ValueError: 82 return value 83 return value 84 85 @field_validator("related_document", mode="before") 86 @classmethod 87 def _related_document_as_str(cls, value: Any) -> Any: 88 """Accept an integer document ID as well (kept as a string).""" 89 if isinstance(value, int) and not isinstance(value, bool): 90 return str(value) 91 return value
A paperless-ngx background task (e.g. document consumption).
Values are taken from paperless-ngx unaltered; unknown fields are ignored.
Attributes:
- id: Numeric database ID of the task (used by
~easypaperless.resources.TasksResource.acknowledge()). - task_id: Unique Celery task identifier (UUID string), as returned by
documents.upload(wait=False). - task_name: Name of the task, e.g.
"consume_file". - task_file_name: Original file name submitted for processing.
- type: Task type as reported by paperless-ngx:
"auto_task"(e.g. a document consumption),"scheduled_task"or"manual_task". - status: Current task status as a
TaskStatusenum value. A status this library does not know yet is kept as the plain string paperless-ngx sent (it compares equal to that string). - result: Result or error message exactly as paperless-ngx reports it.
Consumption failures start with
"<task_file_name>: ", e.g."Success. New document id 42 created","x.pdf: Not consuming x.pdf: It is a duplicate of y (#12)."(a duplicate of a trashed document ends in" Note: existing document is in the trash.") or"x.pdf: Error occurred while consuming document x.pdf: ...". - acknowledged: Whether the task was acknowledged (dismissed in the UI).
- related_document: Document ID as a string, or
None. OnSUCCESSit is the new document. On a duplicateFAILUREit is the existing document the upload duplicates (Nonewhen that document is in the trash).Nonefor other failures. - date_created: When the task was created.
- date_done: When the task finished,
Nonewhile it is running. - owner: ID of the user owning the task, if any.
13class TaskStatus(StrEnum): 14 """Status values for a paperless-ngx background processing task.""" 15 16 PENDING = "PENDING" 17 STARTED = "STARTED" 18 SUCCESS = "SUCCESS" 19 FAILURE = "FAILURE" 20 RETRY = "RETRY" 21 REVOKED = "REVOKED" 22 RECEIVED = "RECEIVED"
Status values for a paperless-ngx background processing task.
68class UiSettings(BaseModel): 69 """Current user, effective permissions and server settings. 70 71 Returned by :meth:`~easypaperless.PaperlessClient.ui_settings` 72 (``GET /api/ui_settings/``). 73 74 Attributes: 75 user: The user the API token belongs to. 76 permissions: The user's effective permission codenames exactly as 77 paperless-ngx returns them: bare codenames such as 78 ``"add_document"`` or ``"view_paperlesstask"``, including 79 permissions granted via groups. For a superuser paperless lists 80 every permission. Note: codenames are bare (``"add_document"``), 81 unlike the app-labelled ``PaperlessPermission`` form 82 (``"documents.add_document"``). 83 settings: Server-side settings (version, app title, trash delay, ...). 84 """ 85 86 model_config = ConfigDict(extra="ignore") 87 88 user: UiSettingsUser 89 permissions: list[str] = Field(default_factory=list) 90 settings: UiSettingsServerSettings = Field(default_factory=UiSettingsServerSettings) 91 92 def has_permission(self, codename: str) -> bool: 93 """Return whether the user has the permission ``codename``. 94 95 Args: 96 codename: Bare permission codename, e.g. ``"add_note"``. 97 98 Returns: 99 ``True`` if ``codename`` is in :attr:`permissions`, and always 100 ``True`` for a superuser. 101 102 Example: 103 >>> settings.has_permission("add_document") 104 True 105 """ 106 return self.user.is_superuser or codename in self.permissions 107 108 def missing_permissions(self, required: Iterable[str]) -> set[str]: 109 """Return the codenames from ``required`` that the user lacks. 110 111 Args: 112 required: Bare permission codenames the caller needs, e.g. 113 ``{"add_document", "add_note"}``. 114 115 Returns: 116 The subset of ``required`` that is not in :attr:`permissions`. 117 Always an empty set for a superuser. 118 119 Example: 120 >>> settings.missing_permissions({"add_document", "add_note"}) 121 {'add_note'} 122 """ 123 if self.user.is_superuser: 124 return set() 125 return set(required) - set(self.permissions)
Current user, effective permissions and server settings.
Returned by ~easypaperless.PaperlessClient.ui_settings()
(GET /api/ui_settings/).
Attributes:
- user: The user the API token belongs to.
- permissions: The user's effective permission codenames exactly as
paperless-ngx returns them: bare codenames such as
"add_document"or"view_paperlesstask", including permissions granted via groups. For a superuser paperless lists every permission. Note: codenames are bare ("add_document"), unlike the app-labelledPaperlessPermissionform ("documents.add_document"). - settings: Server-side settings (version, app title, trash delay, ...).
92 def has_permission(self, codename: str) -> bool: 93 """Return whether the user has the permission ``codename``. 94 95 Args: 96 codename: Bare permission codename, e.g. ``"add_note"``. 97 98 Returns: 99 ``True`` if ``codename`` is in :attr:`permissions`, and always 100 ``True`` for a superuser. 101 102 Example: 103 >>> settings.has_permission("add_document") 104 True 105 """ 106 return self.user.is_superuser or codename in self.permissions
Return whether the user has the permission codename.
Arguments:
- codename: Bare permission codename, e.g.
"add_note".
Returns:
Trueifcodenameis inpermissions, and alwaysTruefor a superuser.
Example:
>>> settings.has_permission("add_document") True
108 def missing_permissions(self, required: Iterable[str]) -> set[str]: 109 """Return the codenames from ``required`` that the user lacks. 110 111 Args: 112 required: Bare permission codenames the caller needs, e.g. 113 ``{"add_document", "add_note"}``. 114 115 Returns: 116 The subset of ``required`` that is not in :attr:`permissions`. 117 Always an empty set for a superuser. 118 119 Example: 120 >>> settings.missing_permissions({"add_document", "add_note"}) 121 {'add_note'} 122 """ 123 if self.user.is_superuser: 124 return set() 125 return set(required) - set(self.permissions)
Return the codenames from required that the user lacks.
Arguments:
- required: Bare permission codenames the caller needs, e.g.
{"add_document", "add_note"}.
Returns:
The subset of
requiredthat is not inpermissions. Always an empty set for a superuser.
Example:
>>> settings.missing_permissions({"add_document", "add_note"}) {'add_note'}
39class UiSettingsServerSettings(BaseModel): 40 """Server-side settings paperless-ngx includes in the UI settings. 41 42 Every field is optional; fields a paperless version does not send stay 43 ``None``. Frontend preferences the user stored in the web UI may appear as 44 additional keys and are ignored. 45 46 Attributes: 47 version: paperless-ngx version, e.g. ``"2.18.2"``. 48 app_title: Custom application title, or ``None`` for the default. 49 app_logo: URL of a custom application logo, or ``None``. 50 trash_delay: Days before trashed documents are deleted for good. 51 auditlog_enabled: Whether the audit log (document history) is enabled. 52 email_enabled: Whether paperless-ngx can send e-mails. 53 update_checking: Update-check configuration as paperless sends it, 54 e.g. ``{"backend_setting": "default"}``. 55 """ 56 57 model_config = ConfigDict(extra="ignore") 58 59 version: str | None = None 60 app_title: str | None = None 61 app_logo: str | None = None 62 trash_delay: int | None = None 63 auditlog_enabled: bool | None = None 64 email_enabled: bool | None = None 65 update_checking: dict[str, Any] | bool | None = None
Server-side settings paperless-ngx includes in the UI settings.
Every field is optional; fields a paperless version does not send stay
None. Frontend preferences the user stored in the web UI may appear as
additional keys and are ignored.
Attributes:
- version: paperless-ngx version, e.g.
"2.18.2". - app_title: Custom application title, or
Nonefor the default. - app_logo: URL of a custom application logo, or
None. - trash_delay: Days before trashed documents are deleted for good.
- auditlog_enabled: Whether the audit log (document history) is enabled.
- email_enabled: Whether paperless-ngx can send e-mails.
- update_checking: Update-check configuration as paperless sends it,
e.g.
{"backend_setting": "default"}.
18class UiSettingsUser(BaseModel): 19 """The user the API token belongs to. 20 21 Attributes: 22 id: User ID. 23 username: Login name. 24 is_staff: Whether the user is a staff member (paperless admin views, 25 e.g. :meth:`~easypaperless.PaperlessClient.system_status`). 26 is_superuser: Whether the user is a superuser (has every permission). 27 groups: IDs of the groups the user belongs to. 28 """ 29 30 model_config = ConfigDict(extra="ignore") 31 32 id: int 33 username: str 34 is_staff: bool = False 35 is_superuser: bool = False 36 groups: list[int] = Field(default_factory=list)
The user the API token belongs to.
Attributes:
- id: User ID.
- username: Login name.
- is_staff: Whether the user is a staff member (paperless admin views,
e.g.
~easypaperless.PaperlessClient.system_status()). - is_superuser: Whether the user is a superuser (has every permission).
- groups: IDs of the groups the user belongs to.
212class User(BaseModel): 213 """A paperless-ngx user account. 214 215 Attributes: 216 id: Unique user ID (set by the API). 217 username: Login username. 218 email: Email address. 219 password: Password field as returned by the API (write-only in practice). 220 first_name: Given name. 221 last_name: Family name. 222 date_joined: Timestamp of account creation. 223 is_staff: Whether the user has staff (admin UI) access. 224 is_active: Whether the account is active. 225 is_superuser: Whether the user has unrestricted superuser access. 226 groups: IDs of groups the user belongs to. 227 user_permissions: Directly assigned permission codenames, without the 228 app label (e.g. ``"view_document"``). 229 inherited_permissions: Permissions inherited from the user's groups, 230 in the app-labelled form (e.g. ``"documents.view_document"``, see 231 :data:`PaperlessPermission`). Read-only, not sent on create/update. 232 is_mfa_enabled: Whether multi-factor authentication is enabled 233 (read-only, not sent on create/update). 234 """ 235 236 model_config = ConfigDict(extra="ignore") 237 238 id: int 239 username: str 240 email: str | None = None 241 password: str | None = None 242 first_name: str | None = None 243 last_name: str | None = None 244 date_joined: datetime | None = None 245 is_staff: bool | None = None 246 is_active: bool | None = None 247 is_superuser: bool | None = None 248 groups: list[int] | None = None 249 user_permissions: list[str] | None = None 250 inherited_permissions: list[str] | None = None 251 is_mfa_enabled: bool | None = None
A paperless-ngx user account.
Attributes:
- id: Unique user ID (set by the API).
- username: Login username.
- email: Email address.
- password: Password field as returned by the API (write-only in practice).
- first_name: Given name.
- last_name: Family name.
- date_joined: Timestamp of account creation.
- is_staff: Whether the user has staff (admin UI) access.
- is_active: Whether the account is active.
- is_superuser: Whether the user has unrestricted superuser access.
- groups: IDs of groups the user belongs to.
- user_permissions: Directly assigned permission codenames, without the
app label (e.g.
"view_document"). - inherited_permissions: Permissions inherited from the user's groups,
in the app-labelled form (e.g.
"documents.view_document", seePaperlessPermission). Read-only, not sent on create/update. - is_mfa_enabled: Whether multi-factor authentication is enabled (read-only, not sent on create/update).
34class PaperlessError(Exception): 35 """Base exception for all easypaperless errors. 36 37 Attributes: 38 status_code: The HTTP status code associated with the error, or 39 ``None`` for non-HTTP errors (e.g. timeouts, local validation). 40 """ 41 42 def __init__(self, message: str, status_code: int | None = None) -> None: 43 """Create a PaperlessError. 44 45 Args: 46 message: Human-readable error description. 47 status_code: HTTP status code, if applicable. 48 """ 49 super().__init__(message) 50 self.status_code = status_code
Base exception for all easypaperless errors.
Attributes:
- status_code: The HTTP status code associated with the error, or
Nonefor non-HTTP errors (e.g. timeouts, local validation).
42 def __init__(self, message: str, status_code: int | None = None) -> None: 43 """Create a PaperlessError. 44 45 Args: 46 message: Human-readable error description. 47 status_code: HTTP status code, if applicable. 48 """ 49 super().__init__(message) 50 self.status_code = status_code
Create a PaperlessError.
Arguments:
- message: Human-readable error description.
- status_code: HTTP status code, if applicable.
53class AuthError(PaperlessError): 54 """Raised on 401 or 403 responses. 55 56 Indicates that the API token is missing or invalid, or that the 57 authenticated user lacks permission for the requested operation. Catch 58 :class:`AuthenticationError` (401) or :class:`PermissionDeniedError` (403) 59 to tell the two cases apart. 60 """
Raised on 401 or 403 responses.
Indicates that the API token is missing or invalid, or that the
authenticated user lacks permission for the requested operation. Catch
AuthenticationError (401) or PermissionDeniedError (403)
to tell the two cases apart.
63class AuthenticationError(AuthError): 64 """Raised on 401 responses: the API token is missing or invalid."""
Raised on 401 responses: the API token is missing or invalid.
67class PermissionDeniedError(AuthError): 68 """Raised on 403 responses: the token is valid but lacks a permission."""
Raised on 403 responses: the token is valid but lacks a permission.
71class BadRequestError(PaperlessError): 72 """Raised on 400 responses: paperless-ngx rejected the request data. 73 74 The message summarises all errors readably, e.g. 75 ``"name: This field is required."``. 76 77 Attributes: 78 field_errors: Mapping of field name to the list of error messages 79 paperless-ngx returned for that field. 80 non_field_errors: Error messages not tied to a single field (the 81 ``non_field_errors`` key, a ``detail`` message, or the items of a 82 plain list body). 83 """ 84 85 def __init__( 86 self, 87 message: str, 88 status_code: int | None = 400, 89 *, 90 field_errors: dict[str, list[str]] | None = None, 91 non_field_errors: list[str] | None = None, 92 ) -> None: 93 """Create a BadRequestError. 94 95 Args: 96 message: Human-readable error description. 97 status_code: HTTP status code. Default: ``400``. 98 field_errors: Parsed per-field error messages. Default: empty. 99 non_field_errors: Parsed messages not tied to a field. Default: empty. 100 """ 101 super().__init__(message, status_code=status_code) 102 self.field_errors: dict[str, list[str]] = dict(field_errors or {}) 103 self.non_field_errors: list[str] = list(non_field_errors or [])
Raised on 400 responses: paperless-ngx rejected the request data.
The message summarises all errors readably, e.g.
"name: This field is required.".
Attributes:
- field_errors: Mapping of field name to the list of error messages paperless-ngx returned for that field.
- non_field_errors: Error messages not tied to a single field (the
non_field_errorskey, adetailmessage, or the items of a plain list body).
85 def __init__( 86 self, 87 message: str, 88 status_code: int | None = 400, 89 *, 90 field_errors: dict[str, list[str]] | None = None, 91 non_field_errors: list[str] | None = None, 92 ) -> None: 93 """Create a BadRequestError. 94 95 Args: 96 message: Human-readable error description. 97 status_code: HTTP status code. Default: ``400``. 98 field_errors: Parsed per-field error messages. Default: empty. 99 non_field_errors: Parsed messages not tied to a field. Default: empty. 100 """ 101 super().__init__(message, status_code=status_code) 102 self.field_errors: dict[str, list[str]] = dict(field_errors or {}) 103 self.non_field_errors: list[str] = list(non_field_errors or [])
Create a BadRequestError.
Arguments:
- message: Human-readable error description.
- status_code: HTTP status code. Default:
400. - field_errors: Parsed per-field error messages. Default: empty.
- non_field_errors: Parsed messages not tied to a field. Default: empty.
106class NotFoundError(PaperlessError): 107 """Raised on 404 responses or when a name lookup fails."""
Raised on 404 responses or when a name lookup fails.
114class NotPaperlessError(PaperlessError): 115 """Raised when the configured URL does not point to a paperless-ngx instance. 116 117 Raised by :meth:`~easypaperless.PaperlessClient.server_version` when the 118 server answers the API root with 404, or with a successful response that 119 lacks paperless's ``X-Version`` header (e.g. an HTML page from another web 120 app or a reverse proxy). ``status_code`` holds the HTTP status of that 121 response. 122 """
Raised when the configured URL does not point to a paperless-ngx instance.
Raised by ~easypaperless.PaperlessClient.server_version() when the
server answers the API root with 404, or with a successful response that
lacks paperless's X-Version header (e.g. an HTML page from another web
app or a reverse proxy). status_code holds the HTTP status of that
response.
110class ValidationError(PaperlessError): 111 """Raised on 422 responses or bad input supplied by the caller."""
Raised on 422 responses or bad input supplied by the caller.
125class ServerError(PaperlessError): 126 """Raised on 5xx responses or transport errors. 127 128 Catch :class:`ServerResponseError` or :class:`TransportError` to tell the 129 two cases apart. 130 """
Raised on 5xx responses or transport errors.
Catch ServerResponseError or TransportError to tell the
two cases apart.
133class ServerResponseError(ServerError): 134 """Raised on HTTP 5xx responses; ``status_code`` holds the status."""
Raised on HTTP 5xx responses; status_code holds the status.
137class TransportError(ServerError): 138 """Raised when paperless-ngx could not be reached or the connection failed. 139 140 Covers connection refused, DNS failures, TLS errors, protocol errors and 141 timeouts. ``status_code`` is always ``None``; the original ``httpx`` 142 exception is chained as ``__cause__``. 143 """ 144 145 def __init__(self, message: str) -> None: 146 """Create a TransportError. 147 148 Args: 149 message: Human-readable error description. 150 """ 151 super().__init__(message, status_code=None)
Raised when paperless-ngx could not be reached or the connection failed.
Covers connection refused, DNS failures, TLS errors, protocol errors and
timeouts. status_code is always None; the original httpx
exception is chained as __cause__.
145 def __init__(self, message: str) -> None: 146 """Create a TransportError. 147 148 Args: 149 message: Human-readable error description. 150 """ 151 super().__init__(message, status_code=None)
Create a TransportError.
Arguments:
- message: Human-readable error description.
154class TransportTimeoutError(TransportError): 155 """Raised when a request times out (connect, read, write or pool timeout). 156 157 The request may still have been processed by the server. 158 """
Raised when a request times out (connect, read, write or pool timeout).
The request may still have been processed by the server.
161class UploadError(PaperlessError): 162 """Raised when file submission or document processing fails. 163 164 Raised by ``client.tasks.wait()`` (see 165 :meth:`~easypaperless.resources.TasksResource.wait`) and therefore by 166 ``client.documents.upload(wait=True)`` when the paperless-ngx task reports 167 ``FAILURE`` or ``REVOKED``, and by ``upload(wait=True)`` when the task 168 succeeds without returning a document ID. 169 170 Attributes: 171 task: The final :class:`~easypaperless.models.tasks.Task` as reported 172 by paperless-ngx (``task_id``, ``status`` and ``result`` 173 unaltered), or ``None`` if no task is involved. Inspect 174 ``task.result`` to tell failures apart, e.g. a duplicate 175 (``"Not consuming x.pdf: It is a duplicate of y (#12)."``) from an 176 OCR error. 177 """ 178 179 def __init__( 180 self, 181 message: str, 182 status_code: int | None = None, 183 *, 184 task: Task | None = None, 185 ) -> None: 186 """Create an UploadError. 187 188 Args: 189 message: Human-readable error description. 190 status_code: HTTP status code, if applicable. 191 task: The failed task, if the error comes from task processing. 192 """ 193 super().__init__(message, status_code=status_code) 194 self.task = task
Raised when file submission or document processing fails.
Raised by client.tasks.wait() (see
~easypaperless.resources.TasksResource.wait()) and therefore by
client.documents.upload(wait=True) when the paperless-ngx task reports
FAILURE or REVOKED, and by upload(wait=True) when the task
succeeds without returning a document ID.
Attributes:
- task: The final
~easypaperless.models.tasks.Taskas reported by paperless-ngx (task_id,statusandresultunaltered), orNoneif no task is involved. Inspecttask.resultto tell failures apart, e.g. a duplicate ("Not consuming x.pdf: It is a duplicate of y (#12).") from an OCR error.
179 def __init__( 180 self, 181 message: str, 182 status_code: int | None = None, 183 *, 184 task: Task | None = None, 185 ) -> None: 186 """Create an UploadError. 187 188 Args: 189 message: Human-readable error description. 190 status_code: HTTP status code, if applicable. 191 task: The failed task, if the error comes from task processing. 192 """ 193 super().__init__(message, status_code=status_code) 194 self.task = task
Create an UploadError.
Arguments:
- message: Human-readable error description.
- status_code: HTTP status code, if applicable.
- task: The failed task, if the error comes from task processing.
197class TaskTimeoutError(PaperlessError): 198 """Raised when waiting for a task exceeds the configured timeout. 199 200 Raised by ``client.tasks.wait()`` (see 201 :meth:`~easypaperless.resources.TasksResource.wait`) and therefore by 202 ``client.documents.upload(wait=True)`` when the task does not reach a 203 terminal state within ``poll_timeout`` seconds. The task keeps running 204 in paperless-ngx; call ``client.tasks.wait(err.task_id)`` to keep waiting 205 instead of uploading again. 206 207 Attributes: 208 task_id: ID of the task that did not finish in time, or ``None``. 209 timeout: The timeout in seconds that was exceeded, or ``None``. 210 """ 211 212 def __init__( 213 self, 214 message: str, 215 *, 216 task_id: str | None = None, 217 timeout: float | None = None, 218 ) -> None: 219 """Create a TaskTimeoutError. 220 221 Args: 222 message: Human-readable error description. 223 task_id: ID of the task that did not finish in time. 224 timeout: The exceeded timeout in seconds. 225 """ 226 super().__init__(message, status_code=None) 227 self.task_id = task_id 228 self.timeout = timeout
Raised when waiting for a task exceeds the configured timeout.
Raised by client.tasks.wait() (see
~easypaperless.resources.TasksResource.wait()) and therefore by
client.documents.upload(wait=True) when the task does not reach a
terminal state within poll_timeout seconds. The task keeps running
in paperless-ngx; call client.tasks.wait(err.task_id) to keep waiting
instead of uploading again.
Attributes:
- task_id: ID of the task that did not finish in time, or
None. - timeout: The timeout in seconds that was exceeded, or
None.
212 def __init__( 213 self, 214 message: str, 215 *, 216 task_id: str | None = None, 217 timeout: float | None = None, 218 ) -> None: 219 """Create a TaskTimeoutError. 220 221 Args: 222 message: Human-readable error description. 223 task_id: ID of the task that did not finish in time. 224 timeout: The exceeded timeout in seconds. 225 """ 226 super().__init__(message, status_code=None) 227 self.task_id = task_id 228 self.timeout = timeout
Create a TaskTimeoutError.
Arguments:
- message: Human-readable error description.
- task_id: ID of the task that did not finish in time.
- timeout: The exceeded timeout in seconds.
231class RetryExhaustedError(PaperlessError): 232 """Raised when all retry attempts are exhausted. 233 234 Attributes: 235 attempts: Total number of attempts made (initial + retries). 236 url: The URL that was requested. 237 """ 238 239 def __init__(self, message: str, attempts: int, url: str) -> None: 240 """Create a RetryExhaustedError. 241 242 Args: 243 message: Human-readable error description. 244 attempts: Total number of attempts made. 245 url: The URL that was requested. 246 """ 247 super().__init__(message, status_code=None) 248 self.attempts = attempts 249 self.url = url
Raised when all retry attempts are exhausted.
Attributes:
- attempts: Total number of attempts made (initial + retries).
- url: The URL that was requested.
239 def __init__(self, message: str, attempts: int, url: str) -> None: 240 """Create a RetryExhaustedError. 241 242 Args: 243 message: Human-readable error description. 244 attempts: Total number of attempts made. 245 url: The URL that was requested. 246 """ 247 super().__init__(message, status_code=None) 248 self.attempts = attempts 249 self.url = url
Create a RetryExhaustedError.
Arguments:
- message: Human-readable error description.
- attempts: Total number of attempts made.
- url: The URL that was requested.