django-notion-sync 0.1.0__py3-none-any.whl

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 (42) hide show
  1. django_notion_sync-0.1.0.dist-info/METADATA +707 -0
  2. django_notion_sync-0.1.0.dist-info/RECORD +42 -0
  3. django_notion_sync-0.1.0.dist-info/WHEEL +4 -0
  4. django_notion_sync-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. notion_sync/__init__.py +5 -0
  6. notion_sync/admin.py +193 -0
  7. notion_sync/api.py +106 -0
  8. notion_sync/apps.py +27 -0
  9. notion_sync/checks.py +145 -0
  10. notion_sync/client.py +217 -0
  11. notion_sync/conf.py +160 -0
  12. notion_sync/exceptions.py +105 -0
  13. notion_sync/files.py +173 -0
  14. notion_sync/inbound.py +381 -0
  15. notion_sync/management/__init__.py +0 -0
  16. notion_sync/management/commands/__init__.py +0 -0
  17. notion_sync/management/commands/notion_sync_check.py +111 -0
  18. notion_sync/management/commands/notion_sync_drain.py +49 -0
  19. notion_sync/management/commands/notion_sync_process_webhooks.py +26 -0
  20. notion_sync/management/commands/notion_sync_prune.py +26 -0
  21. notion_sync/management/commands/notion_sync_reconcile.py +73 -0
  22. notion_sync/management/commands/notion_sync_webhook_token.py +33 -0
  23. notion_sync/mapping.py +501 -0
  24. notion_sync/migrations/0001_initial.py +101 -0
  25. notion_sync/migrations/0002_model_syncs.py +58 -0
  26. notion_sync/migrations/0003_webhook_event.py +69 -0
  27. notion_sync/migrations/__init__.py +0 -0
  28. notion_sync/models.py +168 -0
  29. notion_sync/outbox.py +442 -0
  30. notion_sync/pages.py +217 -0
  31. notion_sync/py.typed +0 -0
  32. notion_sync/records.py +43 -0
  33. notion_sync/schema.py +52 -0
  34. notion_sync/signals.py +56 -0
  35. notion_sync/sync.py +213 -0
  36. notion_sync/tasks.py +86 -0
  37. notion_sync/templates/admin/notion_sync/webhookevent/change_list.html +8 -0
  38. notion_sync/templates/admin/notion_sync/webhookevent/verification_token.html +39 -0
  39. notion_sync/urls.py +12 -0
  40. notion_sync/values.py +455 -0
  41. notion_sync/views.py +15 -0
  42. notion_sync/webhooks.py +451 -0
@@ -0,0 +1,707 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-notion-sync
3
+ Version: 0.1.0
4
+ Summary: Sync Django models with Notion databases: inline calls, a retrying outbox, and edits synced back through webhooks.
5
+ Project-URL: Homepage, https://github.com/layline-dev/django-notion-sync
6
+ Project-URL: Source, https://github.com/layline-dev/django-notion-sync
7
+ Project-URL: Changelog, https://github.com/layline-dev/django-notion-sync/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/layline-dev/django-notion-sync/issues
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: django,notion,notion-api,outbox,sync,webhooks
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: Django :: 5.2
16
+ Classifier: Framework :: Django :: 6.0
17
+ Classifier: Framework :: Django :: 6.1
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Topic :: Internet :: WWW/HTTP
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.11
30
+ Requires-Dist: django>=5.2
31
+ Requires-Dist: notion-client<4,>=3.1
32
+ Provides-Extra: celery
33
+ Requires-Dist: celery>=5.4; extra == 'celery'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # django-notion-sync
37
+
38
+ A reusable Django app that creates and updates pages in a Notion database.
39
+ Call it inline, or queue the write in an outbox and let a command send it with
40
+ retries. Edits made in Notion can flow back to your models through webhooks,
41
+ a reconcile command, or both.
42
+
43
+ > **Status: early.** The API may still change before 1.0. See
44
+ > [Public API](#public-api) for what is covered and how changes are announced.
45
+
46
+ It writes page properties and file attachments. It does not write page
47
+ content, icons or covers.
48
+
49
+ ## Compatibility
50
+
51
+ | | Supported |
52
+ |---|---|
53
+ | Python | 3.11, 3.12, 3.13, 3.14 |
54
+ | Django | 5.2, 6.0, 6.1 (Django 6.x needs Python 3.12+) |
55
+ | Databases tested | SQLite, PostgreSQL |
56
+ | Notion API version | `2025-09-03` |
57
+ | Notion SDK | [`notion-client`](https://pypi.org/project/notion-client/) 3.x |
58
+
59
+ ## Install
60
+
61
+ ```console
62
+ pip install django-notion-sync
63
+ ```
64
+
65
+ Use `pip install "django-notion-sync[celery]"` to also install Celery.
66
+
67
+ Add the app and run its migration. `django.contrib.contenttypes` must be
68
+ installed too.
69
+
70
+ ```python
71
+ INSTALLED_APPS = [
72
+ # ...
73
+ "django.contrib.contenttypes",
74
+ "notion_sync",
75
+ ]
76
+ ```
77
+
78
+ ```console
79
+ python manage.py migrate notion_sync
80
+ ```
81
+
82
+ ## Set up Notion
83
+
84
+ 1. Create an internal integration at <https://www.notion.so/profile/integrations>
85
+ with the **Read content**, **Insert content** and **Update content**
86
+ capabilities, and copy its token.
87
+ 2. Share the database with the integration (database menu → Connections).
88
+ 3. Copy the database's **data source ID** (database menu → Manage data
89
+ sources → Copy data source ID). This is not the database ID in the URL.
90
+ 4. Optional but recommended: add a text property, for example `External ID`.
91
+ It enables upsert and protects queued creates against duplicates.
92
+
93
+ ## Settings
94
+
95
+ ```python
96
+ NOTION_SYNC = {
97
+ "TARGETS": {
98
+ "inbox": {
99
+ "TOKEN": os.environ["NOTION_INBOX_TOKEN"],
100
+ "DATA_SOURCE_ID": "2f26ee68-df30-4251-aad4-8ddc420cba3d",
101
+ "EXTERNAL_ID_PROPERTY": "External ID", # optional
102
+ "WEBHOOK_VERIFICATION_TOKEN": os.environ.get( # optional, for webhooks
103
+ "NOTION_INBOX_WEBHOOK_TOKEN"
104
+ ),
105
+ },
106
+ },
107
+ }
108
+ ```
109
+
110
+ A target is one data source plus the token that can write to it. You refer to
111
+ it by name in every call. Keep tokens in the environment; the package never
112
+ writes a token to the database, a log line or an exception message.
113
+
114
+ Optional settings, with their defaults:
115
+
116
+ | Setting | Default | Meaning |
117
+ |---|---|---|
118
+ | `NOTION_VERSION` | `"2025-09-03"` | The `Notion-Version` header sent with every request. |
119
+ | `TIMEOUT_SECONDS` | `30` | Timeout for each request to Notion. |
120
+ | `MAX_ATTEMPTS` | `8` | Attempts before a queued write is marked failed. |
121
+ | `RETENTION_DAYS` | `7` | How long sent outbox rows and processed webhook events are kept before `notion_sync_prune` deletes them. |
122
+ | `SCHEMA_CACHE_SECONDS` | `300` | How long a data source's schema stays in Django's cache. `0` turns the cache off. |
123
+ | `SENDING_TIMEOUT_SECONDS` | `600` | After this long, a row still marked as sending is treated as interrupted. |
124
+ | `DISPATCH` | `"command"` | `"celery"` sends each queued row from a Celery task as soon as it commits. |
125
+ | `AUTO_SYNC` | `False` | Default for mappings: queue a sync after a save that changed a mapped field. |
126
+ | `ON_DELETE` | `"nothing"` | Default for mappings: `"archive"` moves the page to the trash when the record is deleted. |
127
+ | `ON_NOTION_TRASH` | `"nothing"` | Default for mappings, when a page is moved to the trash in Notion: `"unlink"` clears the record's page ID, `"delete"` deletes the record. |
128
+ | `WEBHOOK_PROCESSING` | `"inline"` | `"stored"` saves each webhook event and processes it later, from the drain command or Celery. |
129
+ | `RECONCILE_LOOKBACK_HOURS` | `24` | How far back `notion_sync_reconcile` looks by default. `0` reads every page. |
130
+
131
+ Then check the setup. This calls Notion:
132
+
133
+ ```console
134
+ python manage.py notion_sync_check
135
+ ```
136
+
137
+ ### System checks
138
+
139
+ The package also adds Django system checks, which run with `manage.py check`,
140
+ `runserver` and `migrate`, and never call Notion. Run only these with
141
+ `manage.py check --tag notion_sync`.
142
+
143
+ | ID | Problem |
144
+ |---|---|
145
+ | `notion_sync.E001` | `NOTION_SYNC` is invalid: an unknown key, or a value of the wrong type or out of range. |
146
+ | `notion_sync.E002` | A target is invalid: not a dict, an unknown key, or a value of the wrong type. |
147
+ | `notion_sync.E003` | A mapping's `target` is not in `TARGETS`. |
148
+ | `notion_sync.E004` | `DISPATCH` is `"celery"`, but Celery is not installed. |
149
+ | `notion_sync.W001` | A target has no `TOKEN` or `DATA_SOURCE_ID`. It is a warning, not an error, so a build or CI job without the environment variables still runs. |
150
+ | `notion_sync.W002` | `notion_sync.urls` is installed, but the default cache is `LocMemCache` or `DummyCache`. The webhook handshake token and the IDs of events already seen must be shared by every process. |
151
+
152
+ A single-process development server can silence W002 with
153
+ `SILENCED_SYSTEM_CHECKS = ["notion_sync.W002"]`. Without
154
+ `django.contrib.contenttypes` in `INSTALLED_APPS`, the app refuses to start
155
+ and says why.
156
+
157
+ ## Writing pages
158
+
159
+ ```python
160
+ from datetime import date
161
+
162
+ from notion_sync.api import (
163
+ create_page,
164
+ update_page,
165
+ upsert_page,
166
+ archive_page,
167
+ get_page,
168
+ )
169
+ from notion_sync.files import NotionFile
170
+
171
+ page = create_page(
172
+ "inbox",
173
+ {
174
+ "Name": "Checkout button does nothing",
175
+ "Priority": "High",
176
+ "Due": date(2026, 12, 1),
177
+ "Tags": ["bug", "web"],
178
+ "Screenshot": NotionFile(ticket.screenshot),
179
+ },
180
+ )
181
+
182
+ update_page("inbox", page.id, {"Priority": "Low"})
183
+ upsert_page("inbox", "ticket-42", {"Name": "Created or updated by external ID"})
184
+ archive_page("inbox", page.id) # moves the page to the trash
185
+ page = get_page("inbox", page.id) # values come back as plain Python
186
+ ```
187
+
188
+ A returned `Page` has `id`, `url`, `last_edited_time`, `properties`,
189
+ `in_trash` and `data_source_id`.
190
+
191
+ These functions call Notion immediately and raise if it fails. They are not
192
+ retried. To have failures retried, queue the write instead (see below).
193
+
194
+ ### Values
195
+
196
+ Keys are Notion property names. The package reads the data source's schema
197
+ and converts each value by the property's type:
198
+
199
+ | Notion type | Python value |
200
+ |---|---|
201
+ | title, text | `str`. Long text is split into 2,000-character pieces for you. |
202
+ | number | `int`, `float` or `Decimal` |
203
+ | select, status | the option's name |
204
+ | multi-select | a list of option names |
205
+ | date | `date`, `datetime`, or `DateRange(start, end)` from `notion_sync.values` |
206
+ | checkbox | `bool` |
207
+ | URL, email, phone | `str` |
208
+ | person | a list of Notion user IDs |
209
+ | relation | a list of page IDs |
210
+ | files & media | a `NotionFile`, an `https://` URL, or a list of them |
211
+
212
+ `None` clears a property (an empty list for the list types). A naive
213
+ `datetime` is read in Django's current time zone.
214
+
215
+ A new select or multi-select option name is created in Notion when first used;
216
+ option names cannot contain commas. A status option must already exist.
217
+
218
+ Formula, rollup, created/edited time, created/edited by and unique ID
219
+ properties can be read but not written.
220
+
221
+ A value that does not fit raises `NotionValidationError`, naming the property,
222
+ its Notion type and the value, before any page is written.
223
+
224
+ ### Files
225
+
226
+ `NotionFile` takes a model's file field value or a storage path:
227
+
228
+ ```python
229
+ NotionFile(ticket.screenshot)
230
+ NotionFile("uploads/report.pdf") # in the default storage
231
+ NotionFile("uploads/report.pdf", storage="private") # an alias in STORAGES
232
+ ```
233
+
234
+ The bytes are uploaded to Notion, so the file needs no public URL. Notion
235
+ limits files to 5 MiB on free workspaces. Writing a files property replaces
236
+ every file already on it.
237
+
238
+ ### External IDs and upsert
239
+
240
+ With `EXTERNAL_ID_PROPERTY` set on the target, `create_page(...,
241
+ external_id="ticket-42")` stores your ID on the page and `upsert_page` finds
242
+ the page by it. Notion's search can lag a few seconds behind a write, so two
243
+ upserts of a brand-new ID in quick succession can create two pages.
244
+
245
+ ## The outbox
246
+
247
+ Queue a write when it must not be lost or must not slow down a request:
248
+
249
+ ```python
250
+ from notion_sync.api import (
251
+ enqueue_create,
252
+ enqueue_update,
253
+ enqueue_upsert,
254
+ enqueue_archive,
255
+ )
256
+
257
+ enqueue_create("inbox", {"Name": "Queued", "Screenshot": NotionFile(ticket.screenshot)})
258
+ ```
259
+
260
+ Enqueueing only writes a database row. It makes no request to Notion, so it
261
+ works during a Notion outage and takes part in the surrounding transaction.
262
+ A queued file is stored as its storage path, never its bytes, so it must
263
+ already be saved to a storage listed in `STORAGES`.
264
+
265
+ Send the queue with the drain command. Run it every minute from cron or a
266
+ scheduler:
267
+
268
+ ```cron
269
+ * * * * * cd /srv/app && python manage.py notion_sync_drain
270
+ 0 3 * * * cd /srv/app && python manage.py notion_sync_prune
271
+ ```
272
+
273
+ Several drains can run at once on PostgreSQL; each row is sent by only one.
274
+
275
+ ### What happens on failure
276
+
277
+ | Failure | Result |
278
+ |---|---|
279
+ | Rate limit (429) | Retried after the wait Notion asks for. |
280
+ | Server error, timeout, conflict, network down | Retried with a doubling wait: 30 s, 1 min, 2 min … up to 1 hour. |
281
+ | Value does not fit, permission denied, page not found | Marked `failed` at once. |
282
+ | Still failing after `MAX_ATTEMPTS` | Marked `failed`. |
283
+ | The record was deleted, or a newer row replaced this one | Marked `skipped`. |
284
+
285
+ The outbox owns every retry: the Notion SDK's own retries are turned off, so
286
+ one attempt is one request.
287
+
288
+ **Duplicate pages.** Notion can create a page and the response can still be
289
+ lost. If the target has `EXTERNAL_ID_PROPERTY`, every queued create writes an
290
+ ID to it (yours, or the outbox row's), and a retry first looks for a page with
291
+ that ID. If the target has none, a create with an unknown outcome is marked
292
+ `needs_review` and is not sent again; check the database, then delete the row
293
+ or retry it from the admin.
294
+
295
+ Values in a queued write are checked against the Notion schema when the row is
296
+ sent, not when it is queued.
297
+
298
+ ### Signals
299
+
300
+ In `notion_sync.signals`:
301
+
302
+ - `page_synced`: a write succeeded, inline or queued. Arguments: `target`,
303
+ `operation`, `page_id`, `page`, `item` (the outbox row, or `None`) and
304
+ `instance` (the model instance for a model sync, or `None`). For a model
305
+ sync the sender is the model class.
306
+ - `sync_failed`: an outbox row was marked `failed` or `needs_review`.
307
+ Arguments: `item`, `error`.
308
+
309
+ ```python
310
+ from django.dispatch import receiver
311
+ from notion_sync.signals import sync_failed
312
+
313
+
314
+ @receiver(sync_failed)
315
+ def alert(sender, item, error, **kwargs):
316
+ logger.error("Notion sync failed for %s: %s", item.pk, error)
317
+ ```
318
+
319
+ ## Syncing models
320
+
321
+ Add the mixin to a model, then make and run a migration. It adds
322
+ `notion_page_id`, `notion_synced_at` and `notion_last_edited_time`.
323
+
324
+ ```python
325
+ from notion_sync.models import NotionSyncMixin
326
+
327
+
328
+ class Ticket(NotionSyncMixin, models.Model):
329
+ title = models.CharField(max_length=200)
330
+ priority = models.CharField(max_length=10, blank=True)
331
+ screenshot = models.FileField(blank=True)
332
+ status = models.CharField(max_length=20, blank=True)
333
+ user = models.ForeignKey(User, on_delete=models.CASCADE)
334
+ tags = models.ManyToManyField("Tag", blank=True)
335
+ ```
336
+
337
+ Map it in a `notion_mappings.py` module in the same app. The package imports
338
+ that module from every installed app at startup.
339
+
340
+ ```python
341
+ import notion_sync
342
+ from notion_sync import In, NotionMapping, Out
343
+
344
+ from .models import Ticket
345
+
346
+
347
+ @notion_sync.register(Ticket)
348
+ class TicketMapping(NotionMapping):
349
+ target = "inbox"
350
+ fields = {
351
+ "Name": Out("title"),
352
+ "Priority": Out("priority"),
353
+ "Reporter": Out(lambda ticket: ticket.user.email),
354
+ "Screenshot": Out("screenshot", create_only=True),
355
+ "Status": In("status"),
356
+ }
357
+ auto_sync = True # None (the default) uses the AUTO_SYNC setting.
358
+ on_delete = "archive" # None uses the ON_DELETE setting.
359
+ on_notion_trash = "unlink" # None uses the ON_NOTION_TRASH setting.
360
+ ```
361
+
362
+ - `Out(source)` sends a value to Notion. `source` is a field or attribute
363
+ name, a dotted path such as `"user.email"`, a method name (it is called),
364
+ or a callable that takes the instance. A file field becomes a `NotionFile`.
365
+ An empty string becomes `None`, which clears the property.
366
+ - `Out(..., create_only=True)` is sent when the page is created and never
367
+ again. Use it for files, which are otherwise uploaded on every sync.
368
+ - `In(field)` marks a property Notion owns. Its value is written to the
369
+ field when the page changes in Notion (see
370
+ [Syncing Notion edits back](#syncing-notion-edits-back)) and is never sent.
371
+ A field cannot be both sent and received.
372
+
373
+ Then:
374
+
375
+ ```python
376
+ ticket.sync_to_notion() # now; raises on failure; returns the Page
377
+ ticket.enqueue_notion_sync() # through the outbox
378
+ ```
379
+
380
+ The first sync creates the page and stores its ID on the record; later syncs
381
+ update that page. The record is updated with a query, not `save()`, so
382
+ linking never triggers another sync.
383
+
384
+ A queued sync stores a reference to the record, not its values, and reads
385
+ them when the row is sent. A record has at most one pending row: queue it five
386
+ times before the drain runs and it is still one write, carrying the latest
387
+ values. If the record is deleted before then, the row is skipped.
388
+
389
+ If the target has `EXTERNAL_ID_PROPERTY`, the record's external ID is
390
+ `<app label>.<model name>:<primary key>` (override `get_external_id()` to
391
+ change it). A create first looks for a page with that ID, so a page made by an
392
+ attempt whose response was lost is found and linked, not created twice.
393
+
394
+ ### Automatic sync
395
+
396
+ With `auto_sync` on, a save that changed an `Out` field queues a sync. A
397
+ change is judged by the fields the `Out` sources name. If any source is a
398
+ callable, a dotted path or a method, every save counts; set `watch_fields`
399
+ on the mapping to list the fields that matter. A save with `update_fields`
400
+ that names only `In` fields does not count.
401
+
402
+ The row is written in the same transaction as the save, so a rolled-back save
403
+ queues nothing. `QuerySet.update()`, `bulk_update()`, `bulk_create()` and
404
+ fixture loading do not call `save()` and are not seen; queue those records
405
+ yourself.
406
+
407
+ Only saves of the mapped model itself are seen. Adding or removing a
408
+ many-to-many value, or saving a related object that an `Out` source reads
409
+ (such as the `User` behind `"user.email"`), queues nothing. Queue those
410
+ records from your own receiver:
411
+
412
+ ```python
413
+ from django.db.models.signals import m2m_changed, post_save
414
+ from django.dispatch import receiver
415
+
416
+
417
+ @receiver(m2m_changed, sender=Ticket.tags.through)
418
+ def tags_changed(sender, instance, action, **kwargs):
419
+ if action in ("post_add", "post_remove", "post_clear"):
420
+ instance.enqueue_notion_sync()
421
+
422
+
423
+ @receiver(post_save, sender=User)
424
+ def user_changed(sender, instance, **kwargs):
425
+ for ticket in Ticket.objects.filter(user=instance):
426
+ ticket.enqueue_notion_sync()
427
+ ```
428
+
429
+ `enqueue_notion_sync()` writes in the current transaction, and a record with
430
+ a pending row is not queued twice.
431
+
432
+ ### Deletes
433
+
434
+ With `on_delete = "archive"`, deleting a record queues moving its page to the
435
+ trash. A pending sync for the record becomes the archive. A record that was
436
+ never sent to Notion queues nothing. Deleting through a queryset works too:
437
+ Django sends the delete signal for each row.
438
+
439
+ ### Checking mappings
440
+
441
+ `notion_sync_check` also checks every mapping against its target's schema:
442
+ each property exists, can be written (for `Out`), and suits the model
443
+ field's type.
444
+
445
+ ## Syncing Notion edits back
446
+
447
+ Mark the properties Notion owns with `In(field)` on a mapping. When a page
448
+ changes in Notion, the package fetches it, finds the records linked to it by
449
+ `notion_page_id`, and writes each `In` property to its field. There are two
450
+ ways to hear about changes, and they work together:
451
+
452
+ - **Reconcile**: a command you schedule. It needs no public URL.
453
+ - **Webhooks**: Notion calls your site within seconds of a change.
454
+
455
+ Running reconcile on a schedule is a good safety net even with webhooks, as
456
+ Notion does not promise to deliver every event.
457
+
458
+ ### What applying a change does
459
+
460
+ - Only `In` fields and `notion_last_edited_time` are written, with
461
+ `save(update_fields=...)`. That save never queues a sync back to Notion,
462
+ even with `auto_sync`, so the echo of your own write changes nothing.
463
+ - A value that does not fit the field (too long, not a valid choice, empty
464
+ for a field that cannot be empty) is left unchanged and logged as a warning.
465
+ - Notion's events can arrive late or out of order, so the page is always
466
+ fetched fresh. If a record already holds a newer state of the page, an
467
+ older one is skipped. Notion keeps edit times only to the minute, so two
468
+ states with the same edit time cannot be ordered: if one would change a
469
+ field, the page is read again from Notion while the record is locked, and
470
+ that fresh read is applied. A second edit in the same minute is not lost.
471
+ - When a field changes, the record is saved with `save()`, so your own
472
+ `post_save` receivers see it. When only the page's edit time moved, the
473
+ record is updated with a query, so Django sends no `post_save`
474
+ (`page_changed` is still sent).
475
+
476
+ ### Reconcile without a public URL
477
+
478
+ ```console
479
+ python manage.py notion_sync_reconcile # pages edited in the last RECONCILE_LOOKBACK_HOURS
480
+ python manage.py notion_sync_reconcile --target inbox --since 2026-11-20T08:00
481
+ python manage.py notion_sync_reconcile --all # every page
482
+ ```
483
+
484
+ Run it from cron, as often as you want changes to arrive:
485
+
486
+ ```cron
487
+ */5 * * * * cd /srv/app && python manage.py notion_sync_reconcile
488
+ ```
489
+
490
+ Re-reading the same window is harmless: a page already applied changes
491
+ nothing and sends no signal. Reconcile cannot see pages in the trash (Notion
492
+ leaves them out of queries), so `on_notion_trash` and `page_trashed` need
493
+ webhooks.
494
+
495
+ ### Setting up webhooks
496
+
497
+ 1. Include the URL. The endpoint accepts POST only and needs no login or CSRF
498
+ token; every request is checked against Notion's signature instead.
499
+
500
+ ```python
501
+ urlpatterns = [
502
+ # ...
503
+ path("notion/webhook/", include("notion_sync.urls")),
504
+ ]
505
+ ```
506
+
507
+ 2. Deploy, so Notion can reach the URL over HTTPS.
508
+ 3. In Notion, open the integration at
509
+ <https://www.notion.so/profile/integrations>, go to the **Webhooks** tab
510
+ and create a subscription:
511
+ - URL: `https://your.site/notion/webhook/`
512
+ - API version: **2025-09-03** or later. Older versions leave the data
513
+ source out of events, and the package ignores those events (with a
514
+ warning in the log).
515
+ - Events: `page.created`, `page.properties_updated`, `page.moved`,
516
+ `page.deleted` and `page.undeleted`. Other events are accepted and
517
+ ignored.
518
+ 4. Notion sends a one-time verification token to the URL. Within 15 minutes,
519
+ show it with:
520
+
521
+ ```console
522
+ python manage.py notion_sync_webhook_token
523
+ ```
524
+
525
+ or, as a superuser, in the admin: **Webhook events → Webhook verification
526
+ token**. Other staff cannot open that page.
527
+
528
+ The token is held in Django's cache, so the cache must be shared by the
529
+ web processes and wherever you run the command (a local-memory cache is
530
+ not). If nothing arrived, click **Resend token** in Notion. The token is
531
+ never logged, and the package stores it nowhere else.
532
+ 5. Paste the token into Notion's **Verify** dialog, and set it as the
533
+ target's `WEBHOOK_VERIFICATION_TOKEN` (from the environment). Every target
534
+ that shares the integration uses the same token. Redeploy.
535
+
536
+ Until the setting is live, events are answered with 401. Notion retries a
537
+ failed delivery for about a day, so they arrive once you have redeployed,
538
+ and reconcile catches anything else. The package does not accept a token
539
+ from the cache in the meantime: the handshake is not signed, so that would
540
+ let anyone who posted a token sign events.
541
+
542
+ If more than one token is shown, someone else posted to the URL too: the
543
+ handshake request is not signed. Only the token Notion accepts in its Verify
544
+ dialog is real.
545
+
546
+ From then on each request must carry a valid `X-Notion-Signature`, or it is
547
+ answered with 401. An event is routed to the target whose data source holds
548
+ the page; events for other data sources are ignored. Each event is handled
549
+ once: a repeated delivery of the same event, or one older than 48 hours, is
550
+ ignored.
551
+
552
+ ### Processing events inline or later
553
+
554
+ With `WEBHOOK_PROCESSING = "inline"` (the default), the page is fetched and
555
+ applied while Notion waits. If Notion cannot be reached the view answers 503
556
+ and Notion delivers the event again later. Seen event IDs are kept in Django's
557
+ cache for 48 hours; use a cache shared by all web processes.
558
+
559
+ With `"stored"`, the view saves a `WebhookEvent` and answers at once. Process
560
+ the stored events with either command (the drain does the outbox first, then
561
+ the events):
562
+
563
+ ```cron
564
+ * * * * * cd /srv/app && python manage.py notion_sync_drain
565
+ * * * * * cd /srv/app && python manage.py notion_sync_process_webhooks # events only
566
+ ```
567
+
568
+ With `DISPATCH = "celery"`, each stored event is also processed by a task as
569
+ soon as it is saved. A failed event is retried with the outbox's backoff up
570
+ to `MAX_ATTEMPTS`, then marked failed and left for you in the admin.
571
+
572
+ ### When a page is trashed in Notion
573
+
574
+ A `page.deleted` event sends `page_trashed`, then applies the mapping's
575
+ `on_notion_trash`:
576
+
577
+ | Value | Result |
578
+ |---|---|
579
+ | `"nothing"` | The record keeps its page ID. |
580
+ | `"unlink"` | The record's `notion_page_id` is cleared. Its next sync creates a new page. Restoring the page in Notion does not link it again. |
581
+ | `"delete"` | The record is deleted. No archive is queued for it, even with `on_delete = "archive"`, as the page is already in the trash. |
582
+
583
+ ### Inbound signals
584
+
585
+ In `notion_sync.signals`:
586
+
587
+ - `page_changed`: a page changed in Notion. Arguments: `target`, `page` (the
588
+ fetched `Page`), `event_type` (such as `"page.properties_updated"`, or
589
+ `"reconcile"`), `instance` (the linked record, or `None`) and
590
+ `changed_fields` (the model fields that were updated, possibly empty). For
591
+ a linked record the sender is its model class. It is sent when an `In`
592
+ field changed or the page's edit time moved on, and for every webhook
593
+ event about a page no record is linked to. Reconcile does not send it for
594
+ unlinked pages.
595
+ - `page_trashed`: a page was moved to the trash. Arguments: `target`,
596
+ `page`, `event_type` and `instance` (or `None`). Sent before
597
+ `on_notion_trash` is applied.
598
+
599
+ ```python
600
+ from django.dispatch import receiver
601
+ from notion_sync.signals import page_changed
602
+
603
+
604
+ @receiver(page_changed)
605
+ def status_changed(sender, instance, changed_fields, **kwargs):
606
+ if instance is not None and "status" in changed_fields:
607
+ notify_reporter(instance)
608
+ ```
609
+
610
+ ## Celery
611
+
612
+ Install the `celery` extra and set `"DISPATCH": "celery"`. Each queued row
613
+ is then sent by the `send_outbox_item` task as soon as its transaction
614
+ commits. Failed rows wait for their backoff, so also run `drain_outbox` on a
615
+ schedule:
616
+
617
+ ```python
618
+ CELERY_BEAT_SCHEDULE = {
619
+ "notion-sync-drain": {
620
+ "task": "notion_sync.tasks.drain_outbox",
621
+ "schedule": 60.0,
622
+ },
623
+ # With WEBHOOK_PROCESSING = "stored":
624
+ "notion-sync-webhooks": {
625
+ "task": "notion_sync.tasks.process_webhook_events",
626
+ "schedule": 60.0,
627
+ },
628
+ # Optional: pull recent Notion edits.
629
+ "notion-sync-reconcile": {
630
+ "task": "notion_sync.tasks.reconcile",
631
+ "schedule": 300.0,
632
+ },
633
+ }
634
+ ```
635
+
636
+ If the task cannot be queued, for example because the broker is down, the row
637
+ stays pending and the next drain sends it. Retries are the outbox's, not
638
+ Celery's. Celery is imported only when `DISPATCH` is `"celery"` or when
639
+ `notion_sync.tasks` is imported. The drain command and the tasks can run at
640
+ the same time.
641
+
642
+ ## Admin
643
+
644
+ With `django.contrib.admin` installed, outbox rows appear under **Notion
645
+ sync**. Filter by status, target and operation, and search by row, page,
646
+ external or record ID. Rows are read-only. The **Retry selected failed rows**
647
+ action sends `failed` and `needs_review` rows again with a fresh set of
648
+ attempts. A retried create still looks for a page an earlier attempt may have
649
+ made.
650
+
651
+ Stored webhook events are listed there too, read-only, with their payload and
652
+ last error. Superusers also get a page showing the token from Notion's
653
+ subscription handshake (see [Setting up webhooks](#setting-up-webhooks)).
654
+ `notion_sync_prune` deletes processed events older than `RETENTION_DAYS`
655
+ (and never sooner than 48 hours); failed events stay.
656
+
657
+ ## Management commands
658
+
659
+ | Command | Does | Options |
660
+ |---|---|---|
661
+ | `notion_sync_check` | Calls Notion and checks each target's token, data source and external ID property, and every mapping against the schema. | `--target NAME` (repeatable) |
662
+ | `notion_sync_drain` | Sends the outbox rows that are due, then processes stored webhook events. | `--limit N`: at most N rows, and N events |
663
+ | `notion_sync_process_webhooks` | Processes stored webhook events only. | `--limit N` |
664
+ | `notion_sync_prune` | Deletes sent and skipped outbox rows, and processed webhook events, older than `RETENTION_DAYS`. Failed ones stay. | `--days N`: override `RETENTION_DAYS` |
665
+ | `notion_sync_reconcile` | Applies `In` fields from pages edited within `RECONCILE_LOOKBACK_HOURS`. | `--target NAME` (repeatable), `--since DATE` or `--all` |
666
+ | `notion_sync_webhook_token` | Shows the token from Notion's webhook handshake. | |
667
+
668
+ ## Public API
669
+
670
+ These names are public, and changes to them follow the policy below:
671
+
672
+ | Import | Names |
673
+ |---|---|
674
+ | `notion_sync` | `NotionMapping`, `Out`, `In`, `register`, `unregister` |
675
+ | `notion_sync.api` | `create_page`, `update_page`, `upsert_page`, `archive_page`, `get_page`, `enqueue_create`, `enqueue_update`, `enqueue_upsert`, `enqueue_archive` |
676
+ | `notion_sync.models` | `NotionSyncMixin`, `OutboxItem` (with `Operation` and `Status`), `WebhookEvent` (with `Status`) |
677
+ | `notion_sync.files` | `NotionFile` |
678
+ | `notion_sync.pages` | `Page` |
679
+ | `notion_sync.signals` | `page_synced`, `sync_failed`, `page_changed`, `page_trashed` |
680
+ | `notion_sync.exceptions` | `NotionSyncError` and its subclasses |
681
+ | `notion_sync.tasks` | the Celery tasks, by their registered names |
682
+
683
+ The `NOTION_SYNC` setting, the management commands and `notion_sync.urls`
684
+ are public too. Each public module lists its names in `__all__`. Every other
685
+ module, and every name starting with `_`, is internal and can change in any
686
+ release.
687
+
688
+ The package ships type hints (`py.typed`), and the public modules are fully
689
+ typed and checked with mypy.
690
+
691
+ ### Deprecation policy
692
+
693
+ Before 1.0, a minor release (0.x) can make breaking changes. Each one is
694
+ listed under **Breaking** in [CHANGELOG.md](https://github.com/layline-dev/django-notion-sync/blob/main/CHANGELOG.md), with what to change.
695
+ From 1.0, a public name is deprecated before it is removed: it keeps working
696
+ and raises a `DeprecationWarning` for at least one minor release, and is
697
+ removed in a later one.
698
+
699
+ ## Contributing and security
700
+
701
+ To set up a development environment, run the tests or send a change, see
702
+ [CONTRIBUTING.md](https://github.com/layline-dev/django-notion-sync/blob/main/CONTRIBUTING.md). To report a vulnerability privately, see
703
+ [SECURITY.md](https://github.com/layline-dev/django-notion-sync/blob/main/SECURITY.md).
704
+
705
+ ## License
706
+
707
+ MIT. See [LICENSE](https://github.com/layline-dev/django-notion-sync/blob/main/LICENSE).