changeset 799:ecf431e1bd44

python sample for ReceivedInstanceCallback
author Alain Mazy <am@osimis.io>
date Tue, 14 Dec 2021 22:22:37 +0100
parents 80b9ceeb4045
children 83beec704c98
files Sphinx/source/plugins/python.rst Sphinx/source/plugins/python/received-instance-callback.py
diffstat 2 files changed, 49 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/Sphinx/source/plugins/python.rst	Tue Dec 14 17:37:24 2021 +0100
+++ b/Sphinx/source/plugins/python.rst	Tue Dec 14 22:22:37 2021 +0100
@@ -755,6 +755,22 @@
 takes its values from the ``orthanc.ContentType`` enumeration.
 
 
+.. _python_received_instance:
+
+Modifying received instances (new in 3.5 - not released yet)
+...........................................
+
+Starting with release 3.5 of the Python plugin, it is possible to
+modify instances received by Orthanc before they are stored in
+the storage.  This is usually easier to perform modification at this
+stage compared to using the ``/modify`` route once the instances
+has been stored.
+
+.. literalinclude:: python/received-instance-callback.py
+                    :language: python
+
+
+
 Performance and concurrency
 ---------------------------
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Sphinx/source/plugins/python/received-instance-callback.py	Tue Dec 14 22:22:37 2021 +0100
@@ -0,0 +1,33 @@
+from io import BytesIO
+
+from pydicom import dcmread, dcmwrite
+from pydicom.filebase import DicomFileLike
+
+
+# from https://pydicom.github.io/pydicom/stable/auto_examples/memory_dataset.html
+def write_dataset_to_bytes(dataset):
+    with BytesIO() as buffer:
+        memory_dataset = DicomFileLike(buffer)
+        dcmwrite(memory_dataset, dataset)
+        memory_dataset.seek(0)
+
+        return memory_dataset.read()
+
+
+def ReceivedInstanceCallback(receivedDicom):
+
+    dataset = dcmread(BytesIO(receivedDicom))
+
+    if dataset.PatientID.startswith('001-'):
+        return orthanc.ReceivedInstanceCallbackResult.DISCARD, None
+
+    if dataset.PatientID.startswith('002-'):
+        return orthanc.ReceivedInstanceCallbackResult.KEEP_AS_IS, None
+
+    dataset.PatientName = str(dataset.PatientName).upper()
+    dataset.PatientID = '002-' + dataset.PatientID
+    dataset.InstitutionName = "MY INSTITUTION"
+
+    return orthanc.ReceivedInstanceCallbackResult.MODIFIED, write_dataset_to_bytes(dataset)
+
+orthanc.RegisterReceivedInstanceCallback(ReceivedInstanceCallback)