def handle(self, *args, **options): config = settings.MLLP_SOCKETS server = LLPServer(config) self.dispatcher = Dispatcher() if options['postmortem']: try: self.postmortem = True server.dispatch(self.recv_handler) except: pdb.post_mortem() raise else: server.dispatch(self.recv_handler)
class Command(BaseCommand): args = 'runmllpserver' help = """Run a server communicating with a HL7 server to dispatch messages. Usage:\n\n\tdjango [options] runmllpserver [--pdb] --pdb for postmortem debugger """ option_list = BaseCommand.option_list + ( make_option('--pdb', action='store_true', dest='postmortem', default=False, help='Post mortem debugger on error'), ) postmortem = False def handle(self, *args, **options): config = settings.MLLP_SOCKETS server = LLPServer(config) self.dispatcher = Dispatcher() if options['postmortem']: try: self.postmortem = True server.dispatch(self.recv_handler) except: pdb.post_mortem() raise else: server.dispatch(self.recv_handler) def recv_handler(self, msg, server, connection): msg = msg.decode('utf-8') logger.debug('RECV: %s', msg.replace(CR, '\n')) # Logic here - parse the message HL7 # perform required validation # Send ack / error message that message received. # If enhanced mode, do the requisite steps to store then ack try: msg = hl7.parse(msg) except: logger.exception('Error parsing message') if self.postmortem: pdb.post_mortem() resp = responses.hl7NAK('AE', 'UNABLE TO PARSE REQUEST') logger.debug('SEND: %s', unicode(resp).replace(CR, '\n')) server._write_frame(connection, unicode(resp).encode('utf-8')) return try: # DISPATCH MESSAGE HERE. Expect an acknowledgement response message - resp = self.dispatcher.dispatch(msg) if resp is None: raise Exception('Application returned and invalid response (None) - response required') logger.debug('SEND: %s', unicode(resp).replace(CR, '\n')) server._write_frame(connection, unicode(resp).encode('utf-8')) return except: logger.exception('Error dispatching message') if self.postmortem: pdb.post_mortem() resp = responses.hl7NAK('AE', 'INTERNAL ERROR PROCESSING REQUEST') logger.debug('SEND: %s', unicode(resp).replace(CR, '\n')) server._write_frame(connection, unicode(resp).encode('utf-8')) return