import sys import traceback import urllib import cgi import dft # this is the directory containing the DICOM data, or None for all cached data base_dir = '/Users/ch/data' class HandlerError: def __init__(self, status, output): self.status = status self.output = output return def application(environ, start_response): try: (status, c_type, output) = handler(environ) except HandlerError, exc: status = exc.status output = exc.output c_type = 'text/plain' except: (exc_type, exc_value, exc_traceback) = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) status = '500 Internal Server Error' output = ''.join(lines) c_type = 'text/plain' response_headers = [('Content-Type', c_type), ('Content-Length', str(len(output)))] if c_type == 'image/nifti': response_headers.append(('Content-Disposition', 'attachment; filename=image.nii')) start_response(status, response_headers) return [output] def handler(environ): if environ['PATH_INFO'] == '' or environ['PATH_INFO'] == '/': return ('200 OK', 'text/html', index(environ)) parts = environ['PATH_INFO'].strip('/').split('/') if len(parts) == 1: return ('200 OK', 'text/html', patient(parts[0])) if len(parts) == 2: return ('200 OK', 'text/html', patient_date_time(parts[0], parts[1])) if len(parts) == 4: if parts[3] == 'nifti': return ('200 OK', 'image/nifti', nifti(parts[0], parts[1], parts[2])) elif parts[3] == 'png': return ('200 OK', 'image/png', png(parts[0], parts[1], parts[2])) raise HandlerError('404 Not Found', "%s not found\n" % environ['PATH_INFO']) def index(environ): patients = {} for s in dft.get_studies(base_dir): patients.setdefault(s.patient_name, []).append(s) output = '' output += 'data\n' output += '\n' output += 'Home\n' output += '
\n' output += '
\n' for p in sorted(patients): output += 'Patient name: %s\n' % (urllib.quote(p.encode('utf-8')), html_unicode(p)) output += '
\n' if len(patients[p]) == 1: output += '1 study\n' else: output += '%d studies' % len(patients[p]) output += '
\n' output += '\n' output += '\n' return output def study_cmp(a, b): if a.date < b.date: return -1 if a.date > b.date: return 1 if a.time < b.time: return -1 if a.time > b.time: return 1 return 0 def html_unicode(u): return cgi.escape(u.encode('utf-8')) def patient(patient): studies = [ s for s in dft.get_studies() if s.patient_name == patient ] if len(studies) == 0: raise HandlerError('404 Not Found', 'patient %s not found\n' % patient) studies.sort(study_cmp) output = '' output += 'data\n' output += '\n' output += 'Home -> Patient %s\n' % html_unicode(studies[0].patient_name) output += '
\n' output += '
\n' output += 'Patient name: %s\n' % html_unicode(studies[0].patient_name) output += '
\n' output += 'Patient ID: %s\n' % html_unicode(studies[0].patient_id) output += '
\n' output += 'Patient birth date: %s\n' % html_unicode(studies[0].patient_birth_date) output += '
\n' output += 'Patient sex: %s\n' % html_unicode(studies[0].patient_sex) output += '
\n' output += '