changeset 2070:7e6afa0beaf6

samples: improved handling of special characters in paths
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 14 Jul 2016 09:05:22 +0200
parents fabf7820d1f1
children 27fd34970c52
files Resources/Samples/Python/ArchiveStudiesInTimeRange.py Resources/Samples/Python/AutoClassify.py Resources/Samples/Python/DownloadAnonymized.py
diffstat 3 files changed, 14 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/Resources/Samples/Python/ArchiveStudiesInTimeRange.py	Wed Jul 13 16:52:39 2016 +0200
+++ b/Resources/Samples/Python/ArchiveStudiesInTimeRange.py	Thu Jul 14 09:05:22 2016 +0200
@@ -49,6 +49,12 @@
 CheckIsDate(START)
 CheckIsDate(END)
 
+def GetTag(tags, key):
+    if key in tags:
+        return tags[key]
+    else:
+        return 'No%s' % key
+
 # Loop over the studies
 for studyId in RestToolbox.DoGet('%s/studies' % URL):
     # Retrieve the DICOM tags of the current study
@@ -61,13 +67,13 @@
     studyDate = study['StudyDate'][:8]
     if studyDate >= START and studyDate <= END:
         # Create a filename
-        filename = '%s - %s %s - %s.zip' % (study['StudyDate'],
-                                            patient['PatientID'],
-                                            patient['PatientName'],
-                                            study['StudyDescription'])
+        filename = '%s - %s %s - %s.zip' % (GetTag(study, 'StudyDate'),
+                                            GetTag(patient, 'PatientID'),
+                                            GetTag(patient, 'PatientName'),
+                                            GetTag(study, 'StudyDescription'))
 
         # Remove any non-ASCII character in the filename
-        filename = filename.encode('ascii', errors = 'replace')
+        filename = filename.encode('ascii', errors = 'replace').translate(None, r"'\/:*?\"<>|!=").strip()
 
         # Download the ZIP archive of the study
         print('Downloading %s' % filename)
--- a/Resources/Samples/Python/AutoClassify.py	Wed Jul 13 16:52:39 2016 +0200
+++ b/Resources/Samples/Python/AutoClassify.py	Thu Jul 14 09:05:22 2016 +0200
@@ -45,7 +45,7 @@
 
 
 def FixPath(p):
-    return p.encode('ascii', 'ignore').strip().decode()
+    return p.encode('ascii', errors = 'replace').translate(None, r"'\/:*?\"<>|!=").strip()
 
 def GetTag(resource, tag):
     if ('MainDicomTags' in resource and
--- a/Resources/Samples/Python/DownloadAnonymized.py	Wed Jul 13 16:52:39 2016 +0200
+++ b/Resources/Samples/Python/DownloadAnonymized.py	Thu Jul 14 09:05:22 2016 +0200
@@ -44,6 +44,5 @@
         # Trigger the download
         print('Downloading %s' % name)
         zipContent = RestToolbox.DoGet('%s/patients/%s/archive' % (URL, patient))
-        f = open(os.path.join('/tmp', name + '.zip'), 'wb')
-        f.write(zipContent)
-        f.close()
+        with open(os.path.join('/tmp', name + '.zip'), 'wb') as f:
+            f.write(zipContent)