dokicasa 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. dokicasa-0.1.0/.gitignore +16 -0
  2. dokicasa-0.1.0/CHANGELOG.md +30 -0
  3. dokicasa-0.1.0/LICENSE +21 -0
  4. dokicasa-0.1.0/PKG-INFO +461 -0
  5. dokicasa-0.1.0/README.md +425 -0
  6. dokicasa-0.1.0/examples/01_visura_catastale.py +15 -0
  7. dokicasa-0.1.0/examples/02_immobili_da_codice_fiscale.py +17 -0
  8. dokicasa-0.1.0/examples/03_ricerca_in_piu_passi.py +18 -0
  9. dokicasa-0.1.0/examples/04_censimento_di_zona.py +37 -0
  10. dokicasa-0.1.0/examples/05_monitoraggi.py +30 -0
  11. dokicasa-0.1.0/examples/06_gestione_errori.py +74 -0
  12. dokicasa-0.1.0/examples/08_webhook_server.py +40 -0
  13. dokicasa-0.1.0/examples/09_partner_sso.py +18 -0
  14. dokicasa-0.1.0/examples/10_risultati_ed_export.py +22 -0
  15. dokicasa-0.1.0/examples/11_prezzi_e_stato_servizio.py +38 -0
  16. dokicasa-0.1.0/examples/12_annullamento_e_ripresa.py +27 -0
  17. dokicasa-0.1.0/examples/_client.py +51 -0
  18. dokicasa-0.1.0/pyproject.toml +89 -0
  19. dokicasa-0.1.0/src/dokicasa/__init__.py +85 -0
  20. dokicasa-0.1.0/src/dokicasa/_async.py +942 -0
  21. dokicasa-0.1.0/src/dokicasa/_config.py +142 -0
  22. dokicasa-0.1.0/src/dokicasa/_core.py +395 -0
  23. dokicasa-0.1.0/src/dokicasa/_endpoints.py +249 -0
  24. dokicasa-0.1.0/src/dokicasa/_files.py +75 -0
  25. dokicasa-0.1.0/src/dokicasa/_sync.py +1052 -0
  26. dokicasa-0.1.0/src/dokicasa/_utils.py +134 -0
  27. dokicasa-0.1.0/src/dokicasa/_version.py +1 -0
  28. dokicasa-0.1.0/src/dokicasa/errors.py +264 -0
  29. dokicasa-0.1.0/src/dokicasa/py.typed +0 -0
  30. dokicasa-0.1.0/src/dokicasa/types.py +425 -0
  31. dokicasa-0.1.0/src/dokicasa/webhooks.py +50 -0
  32. dokicasa-0.1.0/tests/__init__.py +0 -0
  33. dokicasa-0.1.0/tests/conftest.py +24 -0
  34. dokicasa-0.1.0/tests/helpers.py +124 -0
  35. dokicasa-0.1.0/tests/test_async.py +290 -0
  36. dokicasa-0.1.0/tests/test_download.py +122 -0
  37. dokicasa-0.1.0/tests/test_e2e.py +50 -0
  38. dokicasa-0.1.0/tests/test_errors.py +161 -0
  39. dokicasa-0.1.0/tests/test_http.py +313 -0
  40. dokicasa-0.1.0/tests/test_resources.py +153 -0
  41. dokicasa-0.1.0/tests/test_scanner.py +237 -0
  42. dokicasa-0.1.0/tests/test_utils.py +79 -0
  43. dokicasa-0.1.0/tests/test_webhooks_config.py +113 -0
@@ -0,0 +1,16 @@
1
+ .venv/
2
+ venv/
3
+ __pycache__/
4
+ *.py[cod]
5
+ .pytest_cache/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ .coverage
9
+ coverage.xml
10
+ htmlcov/
11
+ dist/
12
+ build/
13
+ *.egg-info/
14
+ .env
15
+ .DS_Store
16
+ *.part
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ Le versioni seguono il [versionamento semantico](https://semver.org/lang/it/).
4
+
5
+ ## 0.1.0 — 27/11/2026
6
+
7
+ Prima versione: porting dell'SDK JavaScript `@dokicasa/sdk` 0.3.1, senza il tempo reale.
8
+
9
+ - Due client con la stessa API: `Dokicasa` (sincrono) e `AsyncDokicasa` (asyncio), sopra un nucleo
10
+ comune senza I/O (richieste, errori, ritentativi, attesa, controllo del servizio).
11
+ - Risorse e metodi uno a uno con l'SDK JS: `scanner` (create, run, wait, get, status, results,
12
+ iterate_results, filters, children, documents, update, delete, retry, export_xls,
13
+ export_xls_particelle, monitor, save_to_database, download_document), `census`, `monitorings`,
14
+ `account`, `system`.
15
+ - Stessi default: timeout 60 s, 3 ritentativi solo sulle letture (una ricerca non viene mai
16
+ rilanciata), `Retry-After` rispettato, polling da 2 a 15 secondi (×1,5), attesa massima 15 minuti.
17
+ - Stessa gerarchia di errori e stessi codici, con `error_from_response` e la stessa mappatura di
18
+ stati e codici. `PermissionError` diventa `PermissionDeniedError`; `TimeoutError` è anche un
19
+ `TimeoutError` di Python; firma non valida → `WebhookSignatureError`.
20
+ - Annullamento con `threading.Event` (sync) e con la cancellazione di asyncio (async).
21
+ - Download in streaming su cartella, file o file aperto, con file `.part` rinominato alla fine e
22
+ nome dal server ripulito dai percorsi.
23
+ - Il token parte solo verso l'API configurata o un host `*.dokicasa.it` in HTTPS; non compare in
24
+ log, errori, `repr` e hook.
25
+ - Partner SSO con `as_user(...)` (header `X-Dokicasa-User`, stesso formato dell'SDK JS).
26
+ - Webhook: `verify_webhook_signature`, `parse_webhook`, `compute_signature` (HMAC-SHA256, confronto
27
+ a tempo costante).
28
+ - Tipizzato (`py.typed`, mypy strict), `TypedDict` per parametri e risposte, unica dipendenza `httpx`.
29
+ - 11 esempi (gli stessi del JS tranne il tempo reale), 143 test unitari con respx, prove
30
+ end-to-end facoltative contro la sandbox.
dokicasa-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dokidoc S.r.l. (DokiCasa)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,461 @@
1
+ Metadata-Version: 2.5
2
+ Name: dokicasa
3
+ Version: 0.1.0
4
+ Summary: SDK Python ufficiale di DokiCasa: Market Scanner (catasto, visure, ispezioni, censimenti, monitoraggi), sincrono e asyncio
5
+ Project-URL: Homepage, https://docs.dokicasa.it/market-scanner
6
+ Project-URL: Documentation, https://docs.dokicasa.it/market-scanner
7
+ Project-URL: Changelog, https://docs.dokicasa.it/market-scanner
8
+ Author-email: "Dokidoc S.r.l. (DokiCasa)" <tech@dokicasa.it>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agenzia-entrate,catasto,dokicasa,ispezione-ipotecaria,market-scanner,real-estate,sdk,sister,visura
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: Italian
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.9
27
+ Requires-Dist: httpx<1,>=0.25
28
+ Provides-Extra: dev
29
+ Requires-Dist: mypy>=1.10; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
31
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: respx>=0.21; extra == 'dev'
34
+ Requires-Dist: ruff>=0.5; extra == 'dev'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # dokicasa: SDK Python del Market Scanner
38
+
39
+ SDK Python ufficiale di [DokiCasa](https://docs.dokicasa.it/market-scanner) per il Market Scanner:
40
+ catasto, visure, ispezioni ipotecarie, note, mappe, censimenti di zona e monitoraggi.
41
+ Lancia la ricerca, ne segue l'avanzamento, ti restituisce il risultato con una sola chiamata e
42
+ scarica i documenti in streaming. Errori, ritentativi, timeout e annullamento sono già gestiti.
43
+
44
+ È il porting dell'SDK JavaScript [`@dokicasa/sdk`](https://docs.dokicasa.it/market-scanner-sdk):
45
+ stesse risorse, stessi metodi, stessi codici di errore, stessi default (vedi la
46
+ [tabella di corrispondenza](#da-javascript-a-python)).
47
+
48
+ | | |
49
+ |---|---|
50
+ | **Pacchetto** | `dokicasa` (import `dokicasa`) |
51
+ | **Python** | 3.9 o superiore, tipizzato (`py.typed`, mypy strict) |
52
+ | **Dipendenze** | solo [`httpx`](https://www.python-httpx.org/) |
53
+ | **Client** | `Dokicasa` (sincrono) e `AsyncDokicasa` (asyncio), stessa API |
54
+ | **Base URL** | `https://api.dokicasa.it` (produzione), `https://api-dev.dokicasa.it` (sandbox) |
55
+ | **Auth** | il tuo token API, come `Authorization: Bearer` (lo mette l'SDK) |
56
+
57
+ > **Prima di tutto, la sandbox.** Con `env="sandbox"` l'SDK usa `api-dev.dokicasa.it`: stesse API
58
+ > della produzione, ma dati di esempio e nessun costo. Il token di prova è nella pagina del
59
+ > [Market Scanner](https://docs.dokicasa.it/market-scanner#test).
60
+
61
+ ## Installazione
62
+
63
+ ```bash
64
+ pip install dokicasa
65
+ ```
66
+
67
+ ## Avvio rapido
68
+
69
+ ### Sincrono
70
+
71
+ ```python
72
+ from dokicasa import Dokicasa
73
+
74
+ # il token si legge da DOKICASA_API_KEY; in alternativa Dokicasa("il-tuo-token")
75
+ with Dokicasa(env="sandbox") as dk: # "production" quando sei pronto
76
+ visura = dk.scanner.run(
77
+ "visura-catasto",
78
+ {"comune": "Roma", "provincia": "RM", "foglio": "123", "particella": "45", "tipo_visura": "ANALITICA"},
79
+ on_progress=lambda p: print(p["status"], p["percentage"]),
80
+ )
81
+ pdf = dk.scanner.download_document(visura, "visure/") # streaming su file
82
+ print(pdf.path, pdf.size)
83
+ ```
84
+
85
+ ### asyncio
86
+
87
+ ```python
88
+ import asyncio
89
+ from dokicasa import AsyncDokicasa
90
+
91
+
92
+ async def main() -> None:
93
+ async with AsyncDokicasa(env="sandbox") as dk:
94
+ visura = await dk.scanner.run("visura-catasto", {...})
95
+ await dk.scanner.download_document(visura, "visure/")
96
+
97
+
98
+ asyncio.run(main())
99
+ ```
100
+
101
+ `run` lancia la ricerca e aspetta che finisca. Per lanciarla e aspettarla in due momenti diversi
102
+ usa `create` e poi `wait(id)`.
103
+
104
+ > **In produzione le ricerche costano.** Ogni `run` / `create` in produzione è una ricerca vera e
105
+ > consuma credito. L'SDK **non rilancia mai da solo una ricerca**: di default ritenta solo le letture.
106
+
107
+ ## Configurazione
108
+
109
+ Di solito basta il token. Ogni altro valore è configurabile:
110
+
111
+ ```python
112
+ import logging
113
+ from dokicasa import Dokicasa, PollingOptions, RetryOptions
114
+
115
+ dk = Dokicasa(
116
+ "xxx", # oppure get_token=lambda: leggi_il_token()
117
+ env="production", # "production" | "sandbox" (o DOKICASA_ENV)
118
+ base_url="https://api.dokicasa.it", # sovrascrive l'ambiente (es. un tuo proxy)
119
+ timeout=60.0, # timeout di ogni chiamata, in secondi
120
+ retry=RetryOptions(max_retries=3, base_delay=0.5, max_delay=10.0), # oppure retry=False
121
+ polling=PollingOptions(interval=2.0, max_interval=15.0, backoff_factor=1.5),
122
+ headers={"X-Correlation-Id": "abc"},
123
+ logger=logging.getLogger("mia-app.dokicasa"),
124
+ on_request=lambda info: None, # hook per log e metriche
125
+ on_response=lambda info: None, # con stato e durata
126
+ http_client=None, # un httpx.Client tuo (proxy, certificati...)
127
+ )
128
+ ```
129
+
130
+ | Opzione | Default | A cosa serve |
131
+ |---|---|---|
132
+ | `api_key` / `get_token` | `DOKICASA_API_KEY` | Autenticazione. `get_token` viene chiamato a ogni richiesta (token rinnovabili); con `AsyncDokicasa` può essere `async`. |
133
+ | `env` | `DOKICASA_ENV`, poi `production` | Sceglie l'URL dell'API. |
134
+ | `timeout` | 60 secondi | Timeout di ogni chiamata HTTP. |
135
+ | `retry` | 3 ritentativi sulle letture | Su rete giù, timeout, 408/425/429/5xx, rispettando `Retry-After`. Attesa esponenziale con jitter (0,5 s → 10 s). `RetryOptions(methods=(...))` per altri metodi, `retry=False` per spegnerli. |
136
+ | `polling` | da 2 a 15 secondi (×1,5) | L'attesa di una ricerca rallenta da sola. |
137
+ | `acting_user` | — | Partner SSO: chiamate per conto di un utente ([vedi sotto](#partner-sso-per-conto-di-un-utente)). |
138
+ | `acting_user_header` | `X-Dokicasa-User` | Nome dell'header per `acting_user`. |
139
+ | `http_client` | uno nuovo | `httpx.Client` / `httpx.AsyncClient` da riusare; l'SDK non lo chiude. |
140
+
141
+ Ogni chiamata dell'SDK ha `User-Agent: dokicasa-python/<versione>`. Il client si chiude con
142
+ `close()` (`aclose()` per l'async) o usandolo come context manager.
143
+
144
+ ## Ricerche
145
+
146
+ I parametri sono quelli dell'API ([elenco dei tipi](https://docs.dokicasa.it/market-scanner#tipi)),
147
+ con un `TypedDict` per ogni tipo di ricerca in `dokicasa.types` (`VisuraCatastoParams`,
148
+ `TaxDataParams`, `MappaCatastoParams`...).
149
+
150
+ ```python
151
+ dk.scanner.run("catasto", {"comune": "Roma", "foglio": "1", "particella": "2", "search_catasto_type": "F"})
152
+ dk.scanner.run("tax-data", {"tax_code": "RSSMRA80A01H501U"})
153
+ dk.scanner.run("ispezione-tax-data", {"tax_code": "...", "provincia": "RM", "comune": "Roma"})
154
+ dk.scanner.run("mappa-catasto", {..., "tipo_richiesta": "ATTUALITA", "tipo_foglio": "INTERO", "formato": "A3"})
155
+ ```
156
+
157
+ **Ricerche in più passi.** Se l'API chiede una scelta (più immobili, sezioni, omonimi), il
158
+ risultato ha `needs_selection`: si rilancia con il valore scelto.
159
+
160
+ ```python
161
+ r = dk.scanner.run("visura-catasto", {**dati, "enable_multi_step": True})
162
+ if r["result"].get("needs_selection"):
163
+ scelta = r["result"]["rows_immobili"][0]["value"]
164
+ r = dk.scanner.run("visura-catasto", {**dati, "selected_value": scelta})
165
+ ```
166
+
167
+ **Risultati, documenti, export.**
168
+
169
+ ```python
170
+ req = dk.scanner.get(request_id) # richiesta completa
171
+ for immobile in dk.scanner.iterate_results(request_id, filters={"categoria": ["A/2"]}):
172
+ ... # tutte le pagine
173
+ filtri = dk.scanner.filters(request_id)["filters"] # valori disponibili
174
+ dk.scanner.export_xls(request_id, {"categoria": ["A/2"]}) # Excel per email (a pagamento)
175
+ dk.scanner.monitor(request_id, []) # monitora tutto (a pagamento)
176
+ ```
177
+
178
+ **Download.** `download_document` accetta la richiesta (usa `result["pdf_path"]`) o un path/URL.
179
+ Il file arriva in streaming, prima in `<nome>.part` e poi rinominato: un download interrotto non
180
+ lascia file a metà.
181
+
182
+ ```python
183
+ f = dk.scanner.download_document(visura, "visure/") # cartella: nome dal server
184
+ f = dk.scanner.download_document(visura, "visura-rossi.pdf")
185
+ with open("visura.pdf", "wb") as out:
186
+ dk.scanner.download_document(visura, out) # file già aperto
187
+ f = dk.scanner.download_document(visura) # in memoria: f.data
188
+ ```
189
+
190
+ Il nome che arriva dal server viene ripulito (niente `../`). Il token parte solo verso l'API
191
+ configurata o un host `*.dokicasa.it` in HTTPS: se un `pdf_path` puntasse altrove, la richiesta
192
+ parte senza credenziali.
193
+
194
+ **Prima di lanciare.** `dk.system.services()` restituisce prezzo e crediti per ogni tipo,
195
+ `dk.system.health()` lo stato di Sister. Con `check_health=True` l'SDK non lancia la ricerca se il
196
+ servizio è fermo, e quindi non spendi.
197
+
198
+ ## Attese, timeout e annullamento
199
+
200
+ ```python
201
+ import threading
202
+
203
+ cancel = threading.Event() # cancel.set() da un altro thread interrompe l'attesa
204
+ r = dk.scanner.run(
205
+ "ispezione-tax-data",
206
+ dati,
207
+ timeout=10 * 60, # attesa massima in secondi (default 15 minuti)
208
+ request_timeout=30, # timeout della chiamata di lancio
209
+ max_consecutive_errors=5, # errori temporanei di fila tollerati durante l'attesa
210
+ throw_on_failure=False, # restituisce la richiesta anche se è finita in ERROR
211
+ cancel=cancel, # AbortError appena l'evento è impostato
212
+ )
213
+ ```
214
+
215
+ - Il polling parte da 2 secondi e rallenta (×1,5) fino a 15 secondi.
216
+ - I 4xx definitivi (richiesta inesistente, di un altro utente) chiudono subito l'attesa.
217
+ - Nel client sincrono `cancel` interrompe le attese e i download; una singola chiamata HTTP già
218
+ partita finisce entro il suo `timeout`.
219
+ - Con `AsyncDokicasa` si annulla come qualsiasi coroutine (`task.cancel()`,
220
+ `asyncio.wait_for(...)`, `asyncio.timeout(...)`), anche a metà di una chiamata HTTP.
221
+
222
+ Annullare l'attesa **non ferma la ricerca**: prosegue lato server e la riprendi con
223
+ `dk.scanner.wait(id)`.
224
+
225
+ ## Censimento e monitoraggi
226
+
227
+ ```python
228
+ padre = dk.census.create()["scanner_request_id"] # o create(search_mode="MULTI_ADDRESS")
229
+ candidati = dk.census.find_addresses(indirizzo="Via Roma", comune="Torino", provincia="TO")
230
+ valore = next(iter(candidati["result"]["addresses"]))
231
+ dk.census.add_address(
232
+ padre, indirizzo="Via Roma", comune="Torino", provincia="TO", address_value=valore, numero_civico="10"
233
+ )
234
+ censimento = dk.census.wait(padre)
235
+
236
+ dk.monitorings.from_catasto(
237
+ comune="Roma", provincia="RM", foglio="1", particella="2", webhook_url="https://example.com/hook"
238
+ )
239
+ lista = dk.monitorings.list(type="IMMOBILE")
240
+ saldo = dk.account.wallet()["wallet"]
241
+ ```
242
+
243
+ Si può avere **un solo censimento alla volta** per utente (`CensusInProgressError`).
244
+
245
+ ## Errori
246
+
247
+ Ogni errore estende `DokicasaError` e ha un `code`; quelli dell'API anche `status`, `body`,
248
+ `method` e `url`. Nessun errore contiene il token.
249
+
250
+ | Classe | Quando | Dati utili |
251
+ |---|---|---|
252
+ | `InsufficientFundsError` | Crediti o saldo insufficienti (`AMOUNT_NOT_ENOUGH`) | `missing_amount`, `wallet_balance`, `total_amount`, `checkout_link` |
253
+ | `ValidationError` | Dati non validi (422), codice fiscale non valido (`INVALID_TAX_CODE`) | `fields`, `is_duplicate` |
254
+ | `CensusInProgressError` | Censimento già in corso (`PENDING_CENSIMENTO`) | |
255
+ | `ServiceUnavailableError` | Sister fermo, in manutenzione o sovraccarico (`SISTER_FORCE_BLOCK`, `SISTER_PROBLEM`, `SEARCH_FAILED`, 503, `SERVICE_DOWN` da `check_health`) | |
256
+ | `RateLimitError` | Troppe richieste (429) | `retry_after_seconds` |
257
+ | `PartnerPricingRequiredError` | Tipo di ricerca non abilitato sul tuo account | `scanner_type` |
258
+ | `AuthenticationError` / `PermissionDeniedError` / `NotFoundError` | 401 / 403 / 404 | |
259
+ | `ServerError` | 5xx dopo i ritentativi | |
260
+ | `ScanFailedError` | Ricerca finita in `ERROR` (`SCAN_FAILED`) o `CANCELLED` (`SCAN_CANCELLED`) | `request` |
261
+ | `TimeoutError` / `AbortError` / `NetworkError` | Tempo scaduto (`TIMEOUT`), annullata (`ABORTED`), rete giù (`NETWORK_ERROR`) | |
262
+ | `WebhookSignatureError` | Firma del webhook non valida (`INVALID_SIGNATURE`) | |
263
+
264
+ ```python
265
+ from dokicasa import InsufficientFundsError, ServiceUnavailableError, ValidationError
266
+
267
+ try:
268
+ dk.scanner.run("visura-catasto", dati)
269
+ except InsufficientFundsError as e:
270
+ apri_checkout(e.checkout_link)
271
+ except ValidationError as e:
272
+ if e.is_duplicate:
273
+ avvisa("Ricerca già in corso")
274
+ else:
275
+ mostra_errori(e.fields) # {"foglio": ["obbligatorio"], ...}
276
+ except ServiceUnavailableError:
277
+ avvisa("Catasto momentaneamente non disponibile")
278
+ ```
279
+
280
+ `dokicasa.TimeoutError` è anche un `TimeoutError` di Python. `error_from_response(status=..., body=...)`
281
+ costruisce l'errore giusto da una risposta qualsiasi, con la stessa mappatura dell'SDK JS.
282
+
283
+ > **Doppioni.** L'API rifiuta una ricerca identica fatta pochi secondi dopo (un'ora per i
284
+ > documenti): `ValidationError` con `is_duplicate == True`. Non è un errore da mostrare come tale.
285
+
286
+ ## Webhook
287
+
288
+ Per non restare in attesa passa `webhook` (o `callback`) alla ricerca. DokiCasa firma la chiamata
289
+ con l'header `Signature`: l'HMAC-SHA256 del **corpo grezzo**, con chiave il tuo token API
290
+ ([dettagli](https://docs.dokicasa.it/market-scanner#webhook)). Verificala sui byte esatti, prima di
291
+ fare `json.loads`. Il confronto è a tempo costante.
292
+
293
+ ### Flask
294
+
295
+ ```python
296
+ import os
297
+ from flask import Flask, abort, request
298
+ from dokicasa import WebhookSignatureError, parse_webhook
299
+
300
+ app = Flask(__name__)
301
+
302
+
303
+ @app.post("/webhook/dokicasa")
304
+ def dokicasa_webhook():
305
+ try:
306
+ evento = parse_webhook(
307
+ request.get_data(), # byte grezzi, non request.json
308
+ signature=request.headers.get("Signature"),
309
+ secret=os.environ["DOKICASA_API_KEY"],
310
+ )
311
+ except WebhookSignatureError:
312
+ abort(401)
313
+ ricerca = evento.get("scanner_request", evento) # webhook completo o callback compatta
314
+ salva_esito(ricerca["id"], ricerca["status"])
315
+ return "", 200
316
+ ```
317
+
318
+ ### FastAPI
319
+
320
+ ```python
321
+ import os
322
+ from fastapi import FastAPI, HTTPException, Request
323
+ from dokicasa import WebhookSignatureError, parse_webhook
324
+
325
+ app = FastAPI()
326
+
327
+
328
+ @app.post("/webhook/dokicasa")
329
+ async def dokicasa_webhook(request: Request) -> dict[str, bool]:
330
+ try:
331
+ evento = parse_webhook(
332
+ await request.body(),
333
+ signature=request.headers.get("Signature"),
334
+ secret=os.environ["DOKICASA_API_KEY"],
335
+ )
336
+ except WebhookSignatureError:
337
+ raise HTTPException(status_code=401)
338
+ ricerca = evento.get("scanner_request", evento)
339
+ await salva_esito(ricerca["id"], ricerca["status"])
340
+ return {"ok": True}
341
+ ```
342
+
343
+ Solo verifica: `verify_webhook_signature(body, signature=..., secret=...)` restituisce `True`/`False`.
344
+ Per i test dei tuoi endpoint: `compute_signature(body, secret)`.
345
+
346
+ ## Partner SSO: per conto di un utente
347
+
348
+ Se i tuoi utenti entrano in DokiCasa con l'[accesso diretto (SSO)](https://docs.dokicasa.it/sso),
349
+ puoi chiamare **per conto di uno di loro** con il tuo token: ricerche e crediti saranno i suoi.
350
+
351
+ ```python
352
+ agente = dk.as_user({"email": "agente@example.com"}) # oppure dk.as_user("<slug>:<id esterno>")
353
+ agente.account.wallet() # o {"source": "wikicasa", "id": 98765}
354
+ agente.scanner.run("catasto", dati)
355
+ ```
356
+
357
+ L'SDK manda l'header `X-Dokicasa-User` (`email:<email>` oppure `<slug del partner>:<id esterno>`).
358
+ `as_user` restituisce una copia del client che condivide le connessioni; il client originale resta
359
+ del partner. Vale solo per gli utenti collegati al tuo account partner; per gli altri la risposta
360
+ è `403 ACTING_USER_FORBIDDEN` (`PermissionDeniedError`). L'header va abilitato da DokiCasa sul tuo
361
+ account partner: chiedilo al tuo referente.
362
+
363
+ ## Log e sicurezza
364
+
365
+ - L'SDK scrive sul logger `dokicasa` del modulo `logging` (ritentativi, errori durante l'attesa):
366
+ `logging.getLogger("dokicasa").setLevel(logging.DEBUG)` per vederli. Il token non compare mai
367
+ nei log, nei messaggi di errore, nel `repr` del client e della configurazione.
368
+ - `on_request` riceve gli header **senza** `Authorization` (il token si aggiunge dopo l'hook): puoi
369
+ loggarli tranquillamente e aggiungerne di tuoi.
370
+ - Il token API vale come una password: tienilo in una variabile d'ambiente, non nel codice.
371
+
372
+ ## Da JavaScript a Python
373
+
374
+ Stesse risorse e stessi metodi, con i nomi in `snake_case`. I tempi sono in **secondi** (in JS in
375
+ millisecondi).
376
+
377
+ | JavaScript (`@dokicasa/sdk`) | Python (`dokicasa`) |
378
+ |---|---|
379
+ | `createClient({ token, environment })` / `new DokicasaClient(...)` | `Dokicasa(api_key, env=...)` / `AsyncDokicasa(...)` |
380
+ | `token`, `getToken` | `api_key` (o `DOKICASA_API_KEY`), `get_token` |
381
+ | `environment: 'sandbox'` | `env="sandbox"` (o `DOKICASA_ENV`) |
382
+ | `timeoutMs: 60000` | `timeout=60.0` |
383
+ | `retry: { maxRetries, baseDelayMs, maxDelayMs, methods, statuses }` | `retry=RetryOptions(max_retries, base_delay, max_delay, methods, statuses)` |
384
+ | `polling: { intervalMs, maxIntervalMs, backoffFactor }` | `polling=PollingOptions(interval, max_interval, backoff_factor)` |
385
+ | `fetch` | `http_client` (un `httpx.Client` / `httpx.AsyncClient`) |
386
+ | `logger` | `logger` (un `logging.Logger`) |
387
+ | `onRequest`, `onResponse` | `on_request`, `on_response` |
388
+ | `actingUser`, `actingUserHeader` | `acting_user`, `acting_user_header` |
389
+ | `dk.as(user)` | `dk.as_user(user)` (`as` è una parola riservata) |
390
+ | `dk.close()` | `dk.close()` / `await adk.aclose()` / `with` |
391
+ | `dk.http.request(method, path, opts)` | `dk.request(method, path, query=, json=, retry=)` |
392
+ | `dk.http.download(path)` | `dk.download(path, dest)` |
393
+ | `dk.http.url(path, query)` | `dk.url(path, query)` |
394
+ | `scanner.create(type, params, { checkHealth, query })` | `scanner.create(type, params, check_health=, query=)` |
395
+ | `scanner.run(type, params, { onProgress, timeoutMs, ... })` | `scanner.run(type, params, on_progress=, timeout=, request_timeout=, ...)` |
396
+ | `scanner.wait(id, { signal, timeoutMs, throwOnFailure, maxConsecutiveErrors })` | `scanner.wait(id, cancel=, timeout=, throw_on_failure=, max_consecutive_errors=)` |
397
+ | `scanner.get` / `status` / `filters` / `children` / `delete` / `retry` | stessi nomi |
398
+ | `scanner.results(id, { page, per_page, filters, include_soppressi })` | `scanner.results(id, page=, per_page=, filters=, include_soppressi=)` |
399
+ | `for await (... of scanner.iterateResults(id))` | `for ... in scanner.iterate_results(id)` / `async for` |
400
+ | `scanner.documents(id, { type })` | `scanner.documents(id, type=)` |
401
+ | `scanner.update(id, { search_mode })` | `scanner.update(id, search_mode=)` |
402
+ | `scanner.exportXls` / `exportXlsParticelle` | `scanner.export_xls` / `export_xls_particelle` |
403
+ | `scanner.monitor(id, { models, name, note })` | `scanner.monitor(id, models, name=, note=, is_from_censimento=)` |
404
+ | `scanner.saveToDatabase(id, models)` | `scanner.save_to_database(id, models)` |
405
+ | `scanner.downloadDocument(req)` → `{ data, filename, contentType }` | `scanner.download_document(req, dest)` → `DownloadedFile(filename, content_type, size, path, data)` |
406
+ | `scanner.watch(id, cb)`, `dk.realtime.*` | non portati: solo polling |
407
+ | `census.create({ searchMode })` | `census.create(search_mode=)` |
408
+ | `census.findAddresses({ indirizzo, comune, provincia })` | `census.find_addresses(indirizzo=, comune=, provincia=)` |
409
+ | `census.addAddress(parentId, {...})` | `census.add_address(parent_id, ...)` |
410
+ | `census.switchToOwners` / `wait` / `list({ text, page })` / `get` | `census.switch_to_owners` / `wait` / `list(text=, page=)` / `get` |
411
+ | `monitorings.list({ page, type, status, text, ... })` | `monitorings.list(page=, type=, status=, text=, ...)` |
412
+ | `monitorings.ids` / `get` / `delete` / `renew` | stessi nomi |
413
+ | `monitorings.setNote` / `setWebhook` / `reactivateAll` / `fromCatasto` | `set_note` / `set_webhook` / `reactivate_all` / `from_catasto` |
414
+ | `account.wallet` / `walletTransactions` / `credits` / `overview` | `wallet` / `wallet_transactions` / `credits` / `overview` |
415
+ | `system.health` / `heartbeat` / `services` / `isMarketScannerDisabled` | `health` / `heartbeat` / `services` / `is_market_scanner_disabled` |
416
+ | `verifyWebhookSignature({ body, signature, secret })` | `verify_webhook_signature(body, signature=, secret=)` |
417
+ | `parseWebhook(...)` (lancia `Error`) | `parse_webhook(...)` (lancia `WebhookSignatureError`) |
418
+ | `formatActingUser`, `errorFromResponse`, `ENVIRONMENTS` | `format_acting_user`, `error_from_response`, `ENVIRONMENTS` |
419
+ | `PermissionError` | `PermissionDeniedError` (per non coprire il `PermissionError` di Python) |
420
+ | `AbortSignal` | `threading.Event` (sync) / cancellazione asyncio |
421
+ | `e.missingAmount`, `e.retryAfterSeconds`, `e.isDuplicate`, `e.scannerType` | `e.missing_amount`, `e.retry_after_seconds`, `e.is_duplicate`, `e.scanner_type` |
422
+
423
+ ## Esempi
424
+
425
+ In `examples/` gli stessi esempi dell'SDK JS (il 07, tempo reale via socket, non c'è):
426
+
427
+ | File | Cosa fa |
428
+ |---|---|
429
+ | `01_visura_catastale.py` | visura, avanzamento, PDF scaricato in streaming |
430
+ | `02_immobili_da_codice_fiscale.py` | immobili da codice fiscale e intestatari di un immobile |
431
+ | `03_ricerca_in_piu_passi.py` | scelta con `needs_selection` e `selected_value` |
432
+ | `04_censimento_di_zona.py` | censimento, indirizzi candidati, risultati pagina per pagina |
433
+ | `05_monitoraggi.py` | monitoraggio da dati catastali, nota, elenco, rimozione |
434
+ | `06_gestione_errori.py` | ogni errore con la sua classe e il messaggio per l'utente |
435
+ | `08_webhook_server.py` | server (solo libreria standard) che verifica la firma dei webhook |
436
+ | `09_partner_sso.py` | chiamate per conto di un utente con `as_user` |
437
+ | `10_risultati_ed_export.py` | filtri, risultati, documenti, export (a pagamento solo con `CON_COSTI=1`) |
438
+ | `11_prezzi_e_stato_servizio.py` | prezzi, stato di Sister e saldo in parallelo con `AsyncDokicasa` |
439
+ | `12_annullamento_e_ripresa.py` | annullare un'attesa con `threading.Event` e riprenderla |
440
+
441
+ ```bash
442
+ cd examples
443
+ DOKICASA_API_KEY=<token sandbox> python 01_visura_catastale.py # DOKICASA_ENV=sandbox di default
444
+ ```
445
+
446
+ ## Sviluppo
447
+
448
+ ```bash
449
+ python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
450
+ .venv/bin/pytest --cov # test unitari (nessuna chiamata vera: server finto con respx)
451
+ .venv/bin/mypy # strict, su sorgenti, test ed esempi
452
+ .venv/bin/ruff check . && .venv/bin/ruff format --check .
453
+ DOKICASA_E2E_API_KEY=<token sandbox> .venv/bin/pytest tests/test_e2e.py # prove contro la sandbox
454
+ ```
455
+
456
+ Le prove end-to-end puntano sempre alla sandbox (`api-dev.dokicasa.it`), mai alla produzione, e
457
+ senza `DOKICASA_E2E_API_KEY` vengono saltate.
458
+
459
+ ## Licenza
460
+
461
+ MIT, © Dokidoc S.r.l. (DokiCasa).