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 User, 57) 58from easypaperless.sync import SyncPaperlessClient 59 60logging.getLogger("easypaperless").addHandler(logging.NullHandler()) 61 62__all__ = [ 63 "__version__", 64 # Clients 65 "PaperlessClient", 66 "SyncPaperlessClient", 67 # Sentinel 68 "UNSET", 69 "Unset", 70 # Models 71 "MatchingAlgorithm", 72 "PagedResult", 73 "AuditLogActor", 74 "AuditLogEntry", 75 "Correspondent", 76 "CustomField", 77 "CustomFieldValue", 78 "Document", 79 "DocumentMetadata", 80 "DocumentNote", 81 "DocumentType", 82 "FieldDataType", 83 "FileMetadataEntry", 84 "Group", 85 "PermissionSet", 86 "SearchHit", 87 "SetPermissions", 88 "StoragePath", 89 "SystemStatus", 90 "SystemStatusDatabase", 91 "SystemStatusMigrations", 92 "SystemStatusStorage", 93 "SystemStatusTasks", 94 "Tag", 95 "Task", 96 "TaskStatus", 97 "User", 98 "PaperlessPermission", 99 # Exceptions 100 "PaperlessError", 101 "AuthError", 102 "AuthenticationError", 103 "PermissionDeniedError", 104 "BadRequestError", 105 "NotFoundError", 106 "NotPaperlessError", 107 "ValidationError", 108 "ServerError", 109 "ServerResponseError", 110 "TransportError", 111 "TransportTimeoutError", 112 "UploadError", 113 "TaskTimeoutError", 114 "RetryExhaustedError", 115]
188class PaperlessClient(_ClientCore): 189 """Async client for the paperless-ngx API. 190 191 Resources are accessible as attributes: 192 193 * ``client.correspondents`` — correspondent CRUD + bulk ops - 194 see `easypaperless.resources.CorrespondentsResource` 195 * ``client.custom_fields`` — custom field CRUD - 196 see `easypaperless.resources.CustomFieldsResource` 197 * ``client.document_types`` — document type CRUD + bulk ops - 198 see `easypaperless.resources.DocumentTypesResource` 199 * ``client.documents`` — document CRUD, bulk ops, upload, download, history - 200 see `easypaperless.resources.DocumentsResource` 201 * ``client.documents.notes`` — document notes - 202 see `easypaperless.resources.NotesResource` 203 * ``client.storage_paths`` — storage path CRUD + bulk ops - 204 see `easypaperless.resources.StoragePathsResource` 205 * ``client.tags`` — tag CRUD + bulk ops - 206 see `easypaperless.resources.TagsResource` 207 * ``client.groups`` — group CRUD - 208 see `easypaperless.resources.GroupsResource` 209 * ``client.users`` — user CRUD - 210 see `easypaperless.resources.UsersResource` 211 * ``client.trash`` — list, restore, and permanently delete trashed documents - 212 see `easypaperless.resources.TrashResource` 213 * ``client.tasks`` — list, get, wait for, and acknowledge background tasks - 214 see `easypaperless.resources.TasksResource` 215 216 Server information is available directly on the client: 217 :meth:`server_version` (connection check) and :meth:`system_status`. 218 219 Use as an async context manager to ensure the underlying HTTP connection 220 pool is closed when you are done: 221 222 Example: 223 async with PaperlessClient(url="http://localhost:8000", api_token="abc") as client: 224 docs = await client.documents.list(max_results=10) 225 """ 226 227 def __init__( 228 self, 229 url: str, 230 api_token: str, 231 *, 232 timeout: float = 30.0, 233 poll_interval: float = 2.0, 234 poll_timeout: float = 60.0, 235 retry_attempts: int = 0, 236 retry_backoff: float = 1.0, 237 retry_on: tuple[type[Exception], ...] | None = None, 238 tenacity_retrying: Any = None, 239 transport: httpx.AsyncBaseTransport | None = None, 240 ) -> None: 241 """Create an async paperless-ngx client. 242 243 Args: 244 url: Base URL of the paperless-ngx instance 245 (e.g. ``"http://localhost:8000"``). 246 api_token: API token. Generate one in paperless-ngx under 247 *Settings → API → Generate Token*. 248 timeout: Default request timeout in seconds. Default: ``30.0``. 249 poll_interval: Seconds between status checks when ``wait=True`` 250 is passed to :meth:`documents.upload`. Default: ``2.0``. 251 poll_timeout: Maximum seconds to wait for a document to finish 252 processing before raising 253 :exc:`~easypaperless.exceptions.TaskTimeoutError`. 254 Default: ``60.0``. 255 retry_attempts: Maximum number of retry attempts after the first 256 failure. ``0`` (the default) disables retrying entirely, 257 preserving backward-compatible behaviour. Requests that 258 create something are never retried: ``documents.upload()``, 259 every resource's ``create()`` and ``documents.notes.create()`` 260 send exactly one request and raise the error, because a retry 261 after a lost response could create a duplicate. 262 retry_backoff: Initial sleep in seconds between retry attempts; 263 doubles on each subsequent attempt. Default: ``1.0``. 264 retry_on: Tuple of exception types that trigger a retry. Defaults 265 to ``(ServerError, httpx.TimeoutException, httpx.ConnectError)``. 266 ``NotFoundError`` is intentionally excluded from the default set 267 so that genuine 404 responses are never silently retried. 268 Note: every ``httpx`` exception is converted inside the HTTP 269 layer before the retry loop sees it — timeouts become 270 :exc:`~easypaperless.exceptions.TransportTimeoutError`, all 271 other ``httpx`` errors (connection refused, DNS, TLS, protocol) 272 become :exc:`~easypaperless.exceptions.TransportError`; both are 273 ``ServerError`` subclasses. The ``httpx`` entries therefore 274 never match on their own: to retry only transport failures but 275 not 5xx responses, pass ``retry_on=(TransportError,)``; to 276 retry only 5xx responses, pass 277 ``retry_on=(ServerResponseError,)``. Retries apply to every 278 request path, including downloads and follow-up pages of 279 paginated lists, except the create requests listed under 280 ``retry_attempts``. 281 tenacity_retrying: An optional pre-configured 282 ``tenacity.AsyncRetrying`` instance. When supplied, the 283 ``retry_attempts``, ``retry_backoff``, and ``retry_on`` 284 parameters are ignored and tenacity drives the retry loop 285 instead. Requests that create something (``upload()``, 286 ``create()``, ``notes.create()``) bypass it and are never 287 retried, as with ``retry_attempts``. Must be ``AsyncRetrying`` — the sync 288 ``tenacity.Retrying`` is not compatible with the async HTTP 289 layer used internally. 290 transport: Optional ``httpx.AsyncBaseTransport`` passed to the 291 internal ``httpx.AsyncClient`` — e.g. an ``httpx.MockTransport`` 292 for tests, or an ``httpx.AsyncHTTPTransport`` with custom proxy, 293 local address or TLS settings. easypaperless still sets the 294 ``Authorization`` header, base URL, timeout, redirect handling 295 and retries. Default: ``None`` (httpx's default transport). 296 297 Example: 298 Testing with a mock transport:: 299 300 def handler(request: httpx.Request) -> httpx.Response: 301 return httpx.Response(200, json={"count": 0, "next": None, 302 "previous": None, "results": []}) 303 304 client = PaperlessClient(url="http://paperless.test", api_token="t", 305 transport=httpx.MockTransport(handler)) 306 """ 307 super().__init__( 308 url, 309 api_token, 310 timeout=timeout, 311 poll_interval=poll_interval, 312 poll_timeout=poll_timeout, 313 retry_attempts=retry_attempts, 314 retry_backoff=retry_backoff, 315 retry_on=retry_on, 316 tenacity_retrying=tenacity_retrying, 317 transport=transport, 318 ) 319 320 async def __aenter__(self) -> PaperlessClient: 321 return self 322 323 async def __aexit__(self, *args: Any) -> None: 324 await self.close() 325 326 async def server_version(self) -> str: 327 """Return the paperless-ngx version and verify URL and token. 328 329 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 330 response header. This is a cheap "test connection" call. 331 332 Returns: 333 The paperless-ngx version string, e.g. ``"2.18.4"``. 334 335 Raises: 336 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 337 to a paperless-ngx instance: the API root answered with 404, or 338 with a response (e.g. an HTML page, also after a redirect) that 339 lacks the ``X-Version`` header. 340 ~easypaperless.exceptions.AuthenticationError: The token was 341 refused (401). 342 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 343 permission (403). 344 ~easypaperless.exceptions.TransportError: The server could not be 345 reached (connection refused, DNS, TLS, timeout). 346 347 Example: 348 >>> version = await client.server_version() 349 >>> print(version) 350 2.18.4 351 """ 352 logger.info("Getting server version") 353 url = f"{self._session.base_url}/" 354 try: 355 # paperless-ngx redirects /api/ to its HTML schema view. Keep the 356 # httpx default "Accept: */*": with "Accept: application/json" the 357 # redirect target answers 406 Not Acceptable (verified in #0050). 358 resp = await self._session.get("/") 359 except NotFoundError as exc: 360 raise NotPaperlessError( 361 f"{url} does not appear to be a paperless-ngx instance: " 362 "the API root answered with 404 Not Found.", 363 status_code=exc.status_code, 364 ) from exc 365 version: str | None = resp.headers.get("X-Version") 366 if not version: 367 raise NotPaperlessError( 368 f"{url} does not appear to be a paperless-ngx instance: " 369 "the response carries no X-Version header.", 370 status_code=resp.status_code, 371 ) 372 return version 373 374 async def system_status(self) -> SystemStatus: 375 """Return paperless-ngx's system status (``GET /api/status/``). 376 377 Covers version, install type, server OS, storage, database, and the 378 health of Redis, Celery, the search index and the classifier. Every 379 field of the returned model is optional; fields a paperless version 380 does not send stay ``None``, unknown fields are ignored. 381 382 Returns: 383 A :class:`~easypaperless.models.system_status.SystemStatus`. 384 385 Raises: 386 ~easypaperless.exceptions.PermissionDeniedError: The token's user 387 is not an administrator (403). ``/api/status/`` requires a 388 staff or superuser account; paperless-ngx answers others with a 389 plain-text ``Insufficient permissions`` body, which becomes the 390 exception message. 391 ~easypaperless.exceptions.AuthenticationError: The token was 392 refused (401). 393 394 Example: 395 >>> status = await client.system_status() 396 >>> status.database.status 397 'OK' 398 """ 399 logger.info("Getting system status") 400 resp = await self._session.get("/status/") 401 return SystemStatus.model_validate(resp.json())
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) and system_status().
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)
227 def __init__( 228 self, 229 url: str, 230 api_token: str, 231 *, 232 timeout: float = 30.0, 233 poll_interval: float = 2.0, 234 poll_timeout: float = 60.0, 235 retry_attempts: int = 0, 236 retry_backoff: float = 1.0, 237 retry_on: tuple[type[Exception], ...] | None = None, 238 tenacity_retrying: Any = None, 239 transport: httpx.AsyncBaseTransport | None = None, 240 ) -> None: 241 """Create an async paperless-ngx client. 242 243 Args: 244 url: Base URL of the paperless-ngx instance 245 (e.g. ``"http://localhost:8000"``). 246 api_token: API token. Generate one in paperless-ngx under 247 *Settings → API → Generate Token*. 248 timeout: Default request timeout in seconds. Default: ``30.0``. 249 poll_interval: Seconds between status checks when ``wait=True`` 250 is passed to :meth:`documents.upload`. Default: ``2.0``. 251 poll_timeout: Maximum seconds to wait for a document to finish 252 processing before raising 253 :exc:`~easypaperless.exceptions.TaskTimeoutError`. 254 Default: ``60.0``. 255 retry_attempts: Maximum number of retry attempts after the first 256 failure. ``0`` (the default) disables retrying entirely, 257 preserving backward-compatible behaviour. Requests that 258 create something are never retried: ``documents.upload()``, 259 every resource's ``create()`` and ``documents.notes.create()`` 260 send exactly one request and raise the error, because a retry 261 after a lost response could create a duplicate. 262 retry_backoff: Initial sleep in seconds between retry attempts; 263 doubles on each subsequent attempt. Default: ``1.0``. 264 retry_on: Tuple of exception types that trigger a retry. Defaults 265 to ``(ServerError, httpx.TimeoutException, httpx.ConnectError)``. 266 ``NotFoundError`` is intentionally excluded from the default set 267 so that genuine 404 responses are never silently retried. 268 Note: every ``httpx`` exception is converted inside the HTTP 269 layer before the retry loop sees it — timeouts become 270 :exc:`~easypaperless.exceptions.TransportTimeoutError`, all 271 other ``httpx`` errors (connection refused, DNS, TLS, protocol) 272 become :exc:`~easypaperless.exceptions.TransportError`; both are 273 ``ServerError`` subclasses. The ``httpx`` entries therefore 274 never match on their own: to retry only transport failures but 275 not 5xx responses, pass ``retry_on=(TransportError,)``; to 276 retry only 5xx responses, pass 277 ``retry_on=(ServerResponseError,)``. Retries apply to every 278 request path, including downloads and follow-up pages of 279 paginated lists, except the create requests listed under 280 ``retry_attempts``. 281 tenacity_retrying: An optional pre-configured 282 ``tenacity.AsyncRetrying`` instance. When supplied, the 283 ``retry_attempts``, ``retry_backoff``, and ``retry_on`` 284 parameters are ignored and tenacity drives the retry loop 285 instead. Requests that create something (``upload()``, 286 ``create()``, ``notes.create()``) bypass it and are never 287 retried, as with ``retry_attempts``. Must be ``AsyncRetrying`` — the sync 288 ``tenacity.Retrying`` is not compatible with the async HTTP 289 layer used internally. 290 transport: Optional ``httpx.AsyncBaseTransport`` passed to the 291 internal ``httpx.AsyncClient`` — e.g. an ``httpx.MockTransport`` 292 for tests, or an ``httpx.AsyncHTTPTransport`` with custom proxy, 293 local address or TLS settings. easypaperless still sets the 294 ``Authorization`` header, base URL, timeout, redirect handling 295 and retries. Default: ``None`` (httpx's default transport). 296 297 Example: 298 Testing with a mock transport:: 299 300 def handler(request: httpx.Request) -> httpx.Response: 301 return httpx.Response(200, json={"count": 0, "next": None, 302 "previous": None, "results": []}) 303 304 client = PaperlessClient(url="http://paperless.test", api_token="t", 305 transport=httpx.MockTransport(handler)) 306 """ 307 super().__init__( 308 url, 309 api_token, 310 timeout=timeout, 311 poll_interval=poll_interval, 312 poll_timeout=poll_timeout, 313 retry_attempts=retry_attempts, 314 retry_backoff=retry_backoff, 315 retry_on=retry_on, 316 tenacity_retrying=tenacity_retrying, 317 transport=transport, 318 )
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))
326 async def server_version(self) -> str: 327 """Return the paperless-ngx version and verify URL and token. 328 329 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 330 response header. This is a cheap "test connection" call. 331 332 Returns: 333 The paperless-ngx version string, e.g. ``"2.18.4"``. 334 335 Raises: 336 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 337 to a paperless-ngx instance: the API root answered with 404, or 338 with a response (e.g. an HTML page, also after a redirect) that 339 lacks the ``X-Version`` header. 340 ~easypaperless.exceptions.AuthenticationError: The token was 341 refused (401). 342 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 343 permission (403). 344 ~easypaperless.exceptions.TransportError: The server could not be 345 reached (connection refused, DNS, TLS, timeout). 346 347 Example: 348 >>> version = await client.server_version() 349 >>> print(version) 350 2.18.4 351 """ 352 logger.info("Getting server version") 353 url = f"{self._session.base_url}/" 354 try: 355 # paperless-ngx redirects /api/ to its HTML schema view. Keep the 356 # httpx default "Accept: */*": with "Accept: application/json" the 357 # redirect target answers 406 Not Acceptable (verified in #0050). 358 resp = await self._session.get("/") 359 except NotFoundError as exc: 360 raise NotPaperlessError( 361 f"{url} does not appear to be a paperless-ngx instance: " 362 "the API root answered with 404 Not Found.", 363 status_code=exc.status_code, 364 ) from exc 365 version: str | None = resp.headers.get("X-Version") 366 if not version: 367 raise NotPaperlessError( 368 f"{url} does not appear to be a paperless-ngx instance: " 369 "the response carries no X-Version header.", 370 status_code=resp.status_code, 371 ) 372 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
374 async def system_status(self) -> SystemStatus: 375 """Return paperless-ngx's system status (``GET /api/status/``). 376 377 Covers version, install type, server OS, storage, database, and the 378 health of Redis, Celery, the search index and the classifier. Every 379 field of the returned model is optional; fields a paperless version 380 does not send stay ``None``, unknown fields are ignored. 381 382 Returns: 383 A :class:`~easypaperless.models.system_status.SystemStatus`. 384 385 Raises: 386 ~easypaperless.exceptions.PermissionDeniedError: The token's user 387 is not an administrator (403). ``/api/status/`` requires a 388 staff or superuser account; paperless-ngx answers others with a 389 plain-text ``Insufficient permissions`` body, which becomes the 390 exception message. 391 ~easypaperless.exceptions.AuthenticationError: The token was 392 refused (401). 393 394 Example: 395 >>> status = await client.system_status() 396 >>> status.database.status 397 'OK' 398 """ 399 logger.info("Getting system status") 400 resp = await self._session.get("/status/") 401 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'
95class SyncPaperlessClient(_SyncCore): 96 """Synchronous interface to paperless-ngx. 97 98 Resources are accessible as attributes: 99 100 * ``client.correspondents`` — correspondent CRUD + bulk ops - 101 see `easypaperless.resources.SyncCorrespondentsResource` 102 * ``client.custom_fields`` — custom field CRUD - 103 see `easypaperless.resources.SyncCustomFieldsResource` 104 * ``client.document_types`` — document type CRUD + bulk ops - 105 see `easypaperless.resources.SyncDocumentTypesResource` 106 * ``client.documents`` — document CRUD, bulk ops, upload, download - 107 see `easypaperless.resources.SyncDocumentsResource` 108 * ``client.documents.notes`` — document notes - 109 see `easypaperless.resources.SyncNotesResource` 110 * ``client.storage_paths`` — storage path CRUD + bulk ops - 111 see `easypaperless.resources.SyncStoragePathsResource` 112 * ``client.tags`` — tag CRUD + bulk ops - 113 see `easypaperless.resources.SyncTagsResource` 114 * ``client.groups`` — group CRUD - 115 see `easypaperless.resources.SyncGroupsResource` 116 * ``client.users`` — user CRUD - 117 see `easypaperless.resources.SyncUsersResource` 118 * ``client.trash`` — list, restore, and permanently delete trashed documents - 119 see `easypaperless.resources.SyncTrashResource` 120 * ``client.tasks`` — list, get, wait for, and acknowledge background tasks - 121 see `easypaperless.resources.SyncTasksResource` 122 123 Server information is available directly on the client: 124 :meth:`server_version` (connection check) and :meth:`system_status`. 125 126 All methods are synchronous wrappers around the async 127 :class:`~easypaperless.client.PaperlessClient`. Operations run on a 128 dedicated background event loop thread so that the httpx connection pool 129 is reused across calls and cleanup works correctly. 130 131 Use as a context manager to ensure proper cleanup: 132 133 Example: 134 with SyncPaperlessClient(url="http://localhost:8000", api_token="abc") as client: 135 tags = client.tags.list() 136 docs = client.documents.list(search="invoice") 137 138 Worker threads: 139 It is safe to construct and use a ``SyncPaperlessClient`` from a 140 worker thread while another event loop runs in the main thread (e.g. 141 a synchronous worker beside FastAPI/uvicorn, or via 142 ``asyncio.to_thread``). Each client owns its own private loop thread. 143 :meth:`close` (or leaving the ``with`` block) closes the connection 144 pool, stops that loop and joins its thread; calling it again is a 145 no-op. 146 147 Note: 148 Cannot be called directly from code running *inside* an event loop 149 (e.g. Jupyter notebooks or an ``async def`` body) — that would block 150 the loop. Use :class:`~easypaperless.client.PaperlessClient` there, 151 or move the sync calls into a worker thread. 152 """ 153 154 def __init__(self, url: str, api_token: str, **kwargs: Any) -> None: 155 """Create a synchronous paperless-ngx client. 156 157 Args: 158 url: Base URL of the paperless-ngx instance 159 (e.g. ``"http://localhost:8000"``). 160 api_token: API token. Generate one in paperless-ngx under 161 *Settings → API → Generate Token*. 162 **kwargs: Additional keyword arguments forwarded to 163 :class:`~easypaperless.client.PaperlessClient` (e.g. 164 ``poll_interval``, ``poll_timeout``, ``retry_attempts``, 165 ``retry_backoff``, ``retry_on``, ``tenacity_retrying``, 166 ``transport``). 167 When using ``tenacity_retrying``, pass a 168 ``tenacity.AsyncRetrying`` instance — the sync 169 ``tenacity.Retrying`` is not compatible because all requests 170 run on an internal async event loop. 171 172 ``retry_attempts`` / ``tenacity_retrying`` never apply to 173 requests that create something: ``documents.upload()``, every 174 resource's ``create()`` and ``documents.notes.create()`` send 175 exactly one request and raise the error, because a retry after 176 a lost response could create a duplicate. 177 178 ``transport`` (``httpx.AsyncBaseTransport | None``): custom or 179 mock transport for the internal ``httpx.AsyncClient``; must be 180 an *async* transport. An ``httpx.MockTransport`` works — its 181 handler is invoked on the client's internal loop thread. 182 Auth, base URL, timeout and retries stay under easypaperless's 183 control. 184 """ 185 super().__init__(url, api_token, **kwargs) 186 187 def __enter__(self) -> SyncPaperlessClient: 188 return self 189 190 def __exit__(self, *args: Any) -> None: 191 self.close() 192 193 def server_version(self) -> str: 194 """Return the paperless-ngx version and verify URL and token. 195 196 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 197 response header. This is a cheap "test connection" call. 198 199 Returns: 200 The paperless-ngx version string, e.g. ``"2.18.4"``. 201 202 Raises: 203 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 204 to a paperless-ngx instance: the API root answered with 404, or 205 with a response (e.g. an HTML page, also after a redirect) that 206 lacks the ``X-Version`` header. 207 ~easypaperless.exceptions.AuthenticationError: The token was 208 refused (401). 209 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 210 permission (403). 211 ~easypaperless.exceptions.TransportError: The server could not be 212 reached (connection refused, DNS, TLS, timeout). 213 214 Example: 215 >>> client.server_version() 216 '2.18.4' 217 """ 218 return self._run(self._async_client.server_version()) 219 220 def system_status(self) -> SystemStatus: 221 """Return paperless-ngx's system status (``GET /api/status/``). 222 223 Covers version, install type, server OS, storage, database, and the 224 health of Redis, Celery, the search index and the classifier. Every 225 field of the returned model is optional; fields a paperless version 226 does not send stay ``None``, unknown fields are ignored. 227 228 Returns: 229 A :class:`~easypaperless.models.system_status.SystemStatus`. 230 231 Raises: 232 ~easypaperless.exceptions.PermissionDeniedError: The token's user 233 is not an administrator (403). ``/api/status/`` requires a 234 staff or superuser account; paperless-ngx answers others with a 235 plain-text ``Insufficient permissions`` body, which becomes the 236 exception message. 237 ~easypaperless.exceptions.AuthenticationError: The token was 238 refused (401). 239 240 Example: 241 >>> client.system_status().database.status 242 'OK' 243 """ 244 return self._run(self._async_client.system_status())
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) and system_status().
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.
154 def __init__(self, url: str, api_token: str, **kwargs: Any) -> None: 155 """Create a synchronous paperless-ngx client. 156 157 Args: 158 url: Base URL of the paperless-ngx instance 159 (e.g. ``"http://localhost:8000"``). 160 api_token: API token. Generate one in paperless-ngx under 161 *Settings → API → Generate Token*. 162 **kwargs: Additional keyword arguments forwarded to 163 :class:`~easypaperless.client.PaperlessClient` (e.g. 164 ``poll_interval``, ``poll_timeout``, ``retry_attempts``, 165 ``retry_backoff``, ``retry_on``, ``tenacity_retrying``, 166 ``transport``). 167 When using ``tenacity_retrying``, pass a 168 ``tenacity.AsyncRetrying`` instance — the sync 169 ``tenacity.Retrying`` is not compatible because all requests 170 run on an internal async event loop. 171 172 ``retry_attempts`` / ``tenacity_retrying`` never apply to 173 requests that create something: ``documents.upload()``, every 174 resource's ``create()`` and ``documents.notes.create()`` send 175 exactly one request and raise the error, because a retry after 176 a lost response could create a duplicate. 177 178 ``transport`` (``httpx.AsyncBaseTransport | None``): custom or 179 mock transport for the internal ``httpx.AsyncClient``; must be 180 an *async* transport. An ``httpx.MockTransport`` works — its 181 handler is invoked on the client's internal loop thread. 182 Auth, base URL, timeout and retries stay under easypaperless's 183 control. 184 """ 185 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.
193 def server_version(self) -> str: 194 """Return the paperless-ngx version and verify URL and token. 195 196 Sends one authenticated ``GET /api/`` and reads the ``X-Version`` 197 response header. This is a cheap "test connection" call. 198 199 Returns: 200 The paperless-ngx version string, e.g. ``"2.18.4"``. 201 202 Raises: 203 ~easypaperless.exceptions.NotPaperlessError: The URL does not point 204 to a paperless-ngx instance: the API root answered with 404, or 205 with a response (e.g. an HTML page, also after a redirect) that 206 lacks the ``X-Version`` header. 207 ~easypaperless.exceptions.AuthenticationError: The token was 208 refused (401). 209 ~easypaperless.exceptions.PermissionDeniedError: The token lacks 210 permission (403). 211 ~easypaperless.exceptions.TransportError: The server could not be 212 reached (connection refused, DNS, TLS, timeout). 213 214 Example: 215 >>> client.server_version() 216 '2.18.4' 217 """ 218 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'
220 def system_status(self) -> SystemStatus: 221 """Return paperless-ngx's system status (``GET /api/status/``). 222 223 Covers version, install type, server OS, storage, database, and the 224 health of Redis, Celery, the search index and the classifier. Every 225 field of the returned model is optional; fields a paperless version 226 does not send stay ``None``, unknown fields are ignored. 227 228 Returns: 229 A :class:`~easypaperless.models.system_status.SystemStatus`. 230 231 Raises: 232 ~easypaperless.exceptions.PermissionDeniedError: The token's user 233 is not an administrator (403). ``/api/status/`` requires a 234 staff or superuser account; paperless-ngx answers others with a 235 plain-text ``Insufficient permissions`` body, which becomes the 236 exception message. 237 ~easypaperless.exceptions.AuthenticationError: The token was 238 refused (401). 239 240 Example: 241 >>> client.system_status().database.status 242 'OK' 243 """ 244 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'
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.
49class AuditLogActor(BaseModel): 50 """The user who performed an audited action. 51 52 Attributes: 53 id: Numeric user ID. 54 username: Username of the actor. 55 """ 56 57 model_config = ConfigDict(extra="ignore") 58 59 id: int 60 username: str
The user who performed an audited action.
Attributes:
- id: Numeric user ID.
- username: Username of the actor.
63class AuditLogEntry(BaseModel): 64 """A single entry in a document's audit log. 65 66 Attributes: 67 id: Unique audit log entry ID. 68 timestamp: When the action occurred. 69 action: Action type (e.g. ``"create"``, ``"update"``). 70 changes: Free-form dict describing what changed. Keys and value 71 shapes vary by action type. 72 actor: The user who performed the action, or ``None`` for 73 system-generated entries. 74 """ 75 76 model_config = ConfigDict(extra="ignore") 77 78 id: int 79 timestamp: datetime 80 action: str 81 changes: dict[str, Any] 82 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.
13class Correspondent(BaseModel): 14 """A paperless-ngx correspondent (sender or recipient of a document). 15 16 Attributes: 17 id: Unique correspondent ID. 18 name: Correspondent name. 19 document_count: Number of documents assigned to this correspondent. 20 last_correspondence: Date of the most recent document assigned here, 21 or ``None``. 22 """ 23 24 model_config = ConfigDict(extra="ignore") 25 26 id: int 27 name: str 28 slug: str | None = None 29 match: str | None = None 30 matching_algorithm: MatchingAlgorithm | None = None 31 is_insensitive: bool | None = None 32 document_count: int | None = None 33 last_correspondence: date | None = None 34 owner: int | None = None 35 user_can_change: bool | 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.
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.
33class CustomFieldValue(BaseModel): 34 """A custom field value attached to a document. 35 36 Attributes: 37 field: ID of the :class:`~easypaperless.models.custom_fields.CustomField` 38 definition. 39 value: The stored value; its Python type depends on the field's 40 ``data_type``. 41 """ 42 43 model_config = ConfigDict(extra="ignore") 44 45 field: int 46 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.
176class Document(BaseModel): 177 """A paperless-ngx document. 178 179 Attributes: 180 id: Unique document ID. 181 title: Document title. 182 content: Full OCR text content, if available. 183 tags: List of tag IDs assigned to this document. 184 document_type: ID of the assigned document type, or ``None``. 185 correspondent: ID of the assigned correspondent, or ``None``. 186 storage_path: ID of the assigned storage path, or ``None``. 187 created: Document creation date (``date`` object). Changed from 188 ``datetime`` to ``date`` in paperless-ngx API v9. 189 created_date: Date portion of creation. **Deprecated** by 190 paperless-ngx as of v9 — use ``created`` instead. Will be 191 removed in a future API version. 192 archive_serial_number: Archive serial number (ASN), or ``None``. 193 custom_fields: List of :class:`CustomFieldValue` instances. 194 notes: User notes attached to this document. 195 search_hit: Full-text search relevance metadata, populated only when 196 the document was returned by a full-text search. 197 metadata: Extended file-level metadata (checksums, sizes, MIME type). 198 ``None`` unless the document was fetched with 199 ``include_metadata=True`` or retrieved via 200 :meth:`~easypaperless._internal.resources.documents.DocumentsResource.get_metadata`. 201 """ 202 203 model_config = ConfigDict(extra="ignore", populate_by_name=True) 204 205 id: int 206 title: str 207 content: str | None = None 208 tags: list[int] = Field(default_factory=list) 209 document_type: int | None = None 210 correspondent: int | None = None 211 storage_path: int | None = None 212 created: date | None = None 213 created_date: date | None = None 214 modified: datetime | None = None 215 added: datetime | None = None 216 archive_serial_number: int | None = None 217 original_file_name: str | None = None 218 archived_file_name: str | None = None 219 owner: int | None = None 220 user_can_change: bool | None = None 221 is_shared_by_requester: bool | None = None 222 notes: list[DocumentNote] = Field(default_factory=list) 223 custom_fields: list[CustomFieldValue] = Field(default_factory=list) 224 search_hit: SearchHit | None = Field(default=None, alias="__search_hit__") 225 metadata: DocumentMetadata | 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().
134class DocumentMetadata(BaseModel): 135 """Extended file-level metadata for a document. 136 137 Returned by ``GET /api/documents/{id}/metadata/`` and optionally attached 138 to a :class:`Document` when 139 :meth:`~easypaperless._internal.resources.documents.DocumentsResource.get` 140 is called with ``include_metadata=True``. 141 142 Because reading metadata requires disk I/O it is **not** included in 143 document list responses; it must be requested explicitly. 144 145 Attributes: 146 original_checksum: MD5 checksum of the original uploaded file. 147 original_size: Size of the original file in bytes. 148 original_mime_type: MIME type of the original file 149 (e.g. ``"application/pdf"``). 150 media_filename: Path of the archived file relative to the 151 paperless-ngx media root. 152 has_archive_version: ``True`` when paperless-ngx has produced an 153 archived (post-processed) PDF in addition to the original. 154 original_metadata: File-level metadata entries extracted from the 155 original document (PDF XMP/info tags, etc.). 156 archive_checksum: MD5 checksum of the archived file, or ``None`` if 157 no archive version exists. 158 archive_size: Size of the archived file in bytes, or ``None``. 159 archive_metadata: File-level metadata entries from the archived 160 document, or ``None``. 161 """ 162 163 model_config = ConfigDict(extra="ignore") 164 165 original_checksum: str | None = None 166 original_size: int | None = None 167 original_mime_type: str | None = None 168 media_filename: str | None = None 169 has_archive_version: bool | None = None 170 original_metadata: list[FileMetadataEntry] = Field(default_factory=list) 171 archive_checksum: str | None = None 172 archive_size: int | None = None 173 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.
85class DocumentNote(BaseModel): 86 """A user note attached to a document. 87 88 Attributes: 89 id: Unique note ID. 90 note: Text content of the note. 91 created: Timestamp when the note was created. 92 document: ID of the parent document. 93 user: ID of the user who created the note. 94 """ 95 96 model_config = ConfigDict(extra="ignore") 97 98 id: int | None = None 99 note: str 100 created: datetime | None = None 101 document: int | None = None 102 user: int | None = None 103 104 @field_validator("user", mode="before") 105 @classmethod 106 def _coerce_user(cls, v: object) -> int | None: 107 if isinstance(v, dict): 108 return v.get("id") 109 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.
11class DocumentType(BaseModel): 12 """A paperless-ngx document type (e.g. Invoice, Receipt, Contract). 13 14 Attributes: 15 id: Unique document-type ID. 16 name: Document-type name. 17 document_count: Number of documents assigned to this document type. 18 """ 19 20 model_config = ConfigDict(extra="ignore") 21 22 id: int 23 name: str 24 slug: str | None = None 25 match: str | None = None 26 matching_algorithm: MatchingAlgorithm | None = None 27 is_insensitive: bool | None = None 28 document_count: int | None = None 29 owner: int | None = None 30 user_can_change: bool | 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.
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.
112class FileMetadataEntry(BaseModel): 113 """A single embedded metadata key-value pair from a document file. 114 115 Paperless-ngx reads file-level metadata (e.g. PDF XMP/info tags) and 116 exposes each entry in this format. ``namespace`` and ``prefix`` are 117 ``None`` for non-namespaced entries. 118 119 Attributes: 120 namespace: XML namespace URI, or ``None``. 121 prefix: Namespace prefix (e.g. ``"pdf"``), or ``None``. 122 key: Metadata key (e.g. ``"Producer"``). 123 value: Metadata value as a string. 124 """ 125 126 model_config = ConfigDict(extra="ignore") 127 128 namespace: str | None = None 129 prefix: str | None = None 130 key: str 131 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.
16class SearchHit(BaseModel): 17 """Full-text search relevance metadata returned alongside a document. 18 19 Attributes: 20 score: Relevance score assigned by the Whoosh FTS engine. 21 highlights: HTML snippet with matching terms highlighted. 22 rank: Position in the result set by relevance. 23 """ 24 25 model_config = ConfigDict(extra="ignore") 26 27 score: float | None = None 28 highlights: str | None = None 29 note_highlights: str | None = None 30 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.
11class StoragePath(BaseModel): 12 """A paperless-ngx storage path — controls where archived files are stored. 13 14 Attributes: 15 id: Unique storage-path ID. 16 name: Storage-path name. 17 path: Template string used to build the storage path, e.g. 18 ``"{created_year}/{correspondent}/{title}"``. 19 document_count: Number of documents using this storage path. 20 """ 21 22 model_config = ConfigDict(extra="ignore") 23 24 id: int 25 name: str 26 slug: str | None = None 27 path: 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
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.
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.
11class Tag(BaseModel): 12 """A paperless-ngx tag. 13 14 Attributes: 15 id: Unique tag ID. 16 name: Tag name. 17 color: Hex colour code used in the UI (e.g. ``"#ff0000"``). 18 is_inbox_tag: If ``True``, newly ingested documents receive this tag 19 automatically until they are processed. 20 document_count: Number of documents currently assigned to this tag. 21 parent: ID of the parent tag for hierarchical tag trees, or ``None``. 22 children: IDs of child tags, or ``None``. 23 """ 24 25 model_config = ConfigDict(extra="ignore") 26 27 id: int 28 name: str 29 slug: str | None = None 30 color: str | None = None 31 text_color: str | None = None 32 match: str | None = None 33 matching_algorithm: MatchingAlgorithm | None = None 34 is_insensitive: bool | None = None 35 is_inbox_tag: bool | None = None 36 document_count: int | None = None 37 owner: int | None = None 38 user_can_change: bool | None = None 39 parent: int | None = None 40 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.
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.
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.