class SessionHandler(DispatchingHandler): """ Handles session auth requests. """ allowed_methods = ('GET','POST',) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))} def create(self,request): username = request.REQUEST.get('username', 'empty') password = request.REQUEST.get('password','empty') user = authenticate(username=username, password=password) try: #success,msg = do_authenticate(request) #if success: # return succeed(msg) if user is not None: observer = Observer.objects.get(user=user) return succeed(observer.uuid) else: logging.warn(msg) return fail(msg) except: msg = "Internal Server Error" logging.error(msg) return error(msg) def read(self,request): success,msg = do_authenticate(request) if success: return succeed(msg) else: return fail(msg)
class ConceptHandler(DispatchingHandler): """ Handles concept requests. """ allowed_methods = ('GET', 'POST') model = Concept form = ConceptForm #fields = ("uuid", "name","data_type",) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class SMTPHandler(BaseHandler): """ Handles encounter requests. """ allowed_methods = ('POST', ) signals = {LOGGER: (EventSignal(), EventSignalHandler(RequestLog))} def create(self, request, *args, **kwargs): return email_notification_submit(request)
class ObserverHandler(DispatchingHandler): """ Handles observer requests. """ allowed_methods = ('GET', 'POST') model = Observer form = ObserverForm fields = ("uuid", ("user",("username",)), ) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class DeviceHandler(DispatchingHandler): """ Handles device requests. """ allowed_methods = ('GET', 'POST', 'PUT') model = Device form = DeviceForm fields = ( "uuid", "name", ) signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))}
class ObservationHandler(DispatchingHandler): allowed_methods = ('GET', 'POST') model = Observation form = ObservationForm fields = ( "uuid", ("encounter",("uuid")), "node", ("concept",("uuid",)), "value_text", "value_complex", "value", ) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class EncounterHandler(DispatchingHandler): """ Handles encounter requests. """ allowed_methods = ('GET', 'POST') model = Encounter form = EncounterForm fields = ("uuid", "concept", "observation", ("subject",("uuid",)), "created", "modified", ("procedure",("title","uuid")), ) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class SubjectHandler(DispatchingHandler): """ Handles subject requests. """ allowed_methods = ('GET', 'POST') fields = ( "uuid", "family_name", "given_name", "gender", "dob", "image", "system_id", ("location",("name","uuid")), ) model = Subject form = SubjectForm signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class PatientHandler(BaseHandler): """ Handles patient requests. """ allowed_methods = ('GET', ) signals = {LOGGER: (EventSignal(), EventSignalHandler(RequestLog))} def read(self, request, id=None, **kwargs): """ Returns zero or more patients from OpenMRS """ try: opener = openmrslib.build_opener(host=settings.OPENMRS_SERVER_URL) query = self.flatten_dict(request.GET) username = query.pop("username") password = query.pop("password") if id and id != 'list': response = opener.getPatient(username, password, id) if openmrslib.OPENMRS_VERSION < 1.8: message = parseOne(response) else: message = response if len(message) == 0: return fail("") else: response = opener.getAllPatients(username, password, query=query) if openmrslib.OPENMRS_VERSION < 1.8: message = parseAll(response) else: message = "" logging.debug("Response: %s" % response) for p in response: logging.debug(p) firstname = p["givenName"] lastname = p["family_name"] gender = p["gender"] birthdate = p["birthdate"] uuid = p["uuid"] patient = "%s%s%s%s%s%s".format( firstname.lower(), birthdate[0:4], birthdate[5:7], birthdate[8:10], lastname.lower(), gender.lower()) message.append(patient) logging.debug("message: %s" % message) return succeed(message) except Exception, e: logging.error("Error: %s" % str(e)) printstack(e) return fail("%s" % e)
class EncounterTaskHandler(DispatchingHandler): allowed_methods = ('GET', 'POST', 'PUT') model = EncounterTask form = EncounterTaskForm fields = ("uuid", ("assigned_to", ("uuid", )), ("subject", ("uuid")), ("encounter", ("uuid")), "status", "due_on", "completed", "procedure") signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))} def create(self, request, uuid=None): if (uuid): return self.update(request, uuid=uuid) else: return DispatchingHandler.create(self, request) def update(self, request, uuid=None, *args, **kwargs): logging.info("update() %s, %s" % (request.method, request.user)) data = self.flatten_dict(request.POST) if 'uuid' in data.keys(): uuid = data.pop['uuid'] logging.info("update() %s" % uuid) obj = self.model.objects.get(uuid=uuid) status = data.pop('status', None) if status: if status.isdigit(): obj.status = Status.objects.get(pk=int(status)) else: obj.status = Status.objects.get(current__icontains=status) encounter = data.pop("encounter", None) logging.debug("....encounter:: %s" % encounter) if (encounter): obj.encounter = Encounter.objects.get(uuid=encounter) assigned_to = data.pop("assigned_to", None) if (assigned_to): obj.assigned_to = Observer.objects.get(uuid=assigned_to) subject = data.pop("subject", None) if (subject): obj.subject = Subject.objects.get(uuid=subject) observer = data.pop("observer", None) if (observer): obj.observer = Observer.objects.get(uuid=observer) for k, v in data.items(): setattr(obj, k, v) obj.save() return succeed(self.model.objects.filter(uuid=uuid))
class ProcedureHandler(DispatchingHandler): allowed_methods = ('GET', 'POST') model = Procedure fields = ("uuid", "title", "description", "src", "version", "author", ) signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))} def _read_by_uuid(self,request,uuid): """ Returns the procedure file instead of the verbose representation on uuid GET requests """ model = getattr(self.__class__, 'model') obj = model.objects.get(uuid=uuid) return open(obj.src.path).read()
class AuthHandler(BaseHandler): """ Handles status and authentication check requests. For working with openMRS versions 1.6+ """ allowed_methods = ('GET', 'POST') signals = {LOGGER: (EventSignal(), EventSignalHandler(RequestLog))} def read(self, request, *args, **kwargs): return self.create(request) def create(self, request, *args, **kwargs): """Validates user credentials with the backing data store. Request parameters: username a valid username password a valid password Parameters: request An authorization check request. """ try: wsname = "sessions" auth = { "username": request.REQUEST.get("username", None), "password": request.REQUEST.get("password", None) } logging.info("username %s" % auth['username']) opener = openmrslib.build_opener(host=settings.OPENMRS_SERVER_URL) return succeed(opener.wsdispatch(wsname, auth=auth)) except Exception, e: msg = "%s" % e logging.error(msg) return fail(msg)
class SurgicalSubjectHandler(DispatchingHandler): """ Handles subject requests. """ allowed_methods = ('GET', 'POST') #fields = ['uuid'] #exclude = ("location") fields = ("uuid", "family_name", "given_name", "gender", "dob", "image", "system_id", ("location",("name","uuid")), "house_number", "family_number", "national_id", "contact_one", "contact_two", "contact_three", "contact_four", ) model = SurgicalSubject form = SurgicalSubjectForm signals = { LOGGER:( EventSignal(), EventSignalHandler(Event))}
class SessionHandler(DispatchingHandler): """ Handles session auth requests. """ allowed_methods = ( 'GET', 'POST', ) signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))} form = SessionForm #model = None def create(self, request): try: content_type = request.META.get('CONTENT_TYPE', None) logging.debug(content_type) is_json = 'json' in content_type logging.debug("is_json: %s" % is_json) if is_json: raw_data = request.read() data = cjson.decode(raw_data) else: data = self.flatten_dict(request.POST) username = data.get('username', 'empty') password = data.get('password', 'empty') if not settings.TARGET == 'SELF': instance = User(username=username) auth = {'username': username, 'password': password} result = backends.create('Session', auth, instance) if not result: return fail([], errors=[ "Observer does not exist", ], code=404) # Create a user or fetch existin and update password user, created = User.objects.get_or_create( username=result.user.username) user.set_password(password) user.save() # should have returned an Observer instance here observers = Observer.objects.filter( user__username=user.username) # If none were returned we need to create the Observer if observers.count() == 0: observer = Observer(user=user, uuid=result.uuid) observer.save() else: # Observer already exists so we don't have to do # anything since password cache is updated observer = observers[0] return succeed(observer.uuid) else: user = authenticate(username=username, password=password) if user is not None: observer = Observer.objects.get(user=user) return succeed(observer.uuid) else: msg = "Invalid credentials" logging.warn(msg) return fail(msg) except Exception as e: msg = "Internal Server Error" logging.error(unicode(e)) logtb() return error(msg) def read(self, request): success, msg = do_authenticate(request) if success: return succeed(msg) else: return fail(msg)
class NotificationHandler(DispatchingHandler): """ Handles notification requests. """ allowed_methods = ('GET', 'POST', 'PUT') model = Notification form = NotificationForm signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))}
class RelationshipCategoryHandler(DispatchingHandler): """ Handles concept relationship category requests. """ allowed_methods = ('GET', 'POST', 'PUT') model = RelationshipCategory form = RelationshipCategoryForm signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))}
class ConceptHandler(DispatchingHandler): """ Handles concept requests. """ allowed_methods = ('GET', 'POST', 'PUT') model = Concept form = ConceptForm signals = {LOGGER: (EventSignal(), EventSignalHandler(Event))}
class SavedProcedureHandler(BaseHandler): """ Handles encounter requests. """ allowed_methods = ('POST', ) signals = {LOGGER: (EventSignal(), EventSignalHandler(RequestLog))} def create(self, request, *args, **kwargs): logging.info("Received saved procedure submission.") response = '' form = ProcedureSubmitForm(self.flatten_dict(request.POST)) logging.debug("Data: %s" % form.data) try: form.full_clean() if not form.is_valid(): raise ValidationError(form._get_errors()) savedproc_guid = form.cleaned_data['savedproc_guid'] procedure_guid = form.cleaned_data['procedure_guid'] responses = form.cleaned_data['responses'] phone = form.cleaned_data['phone'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] result, message = register_saved_procedure(savedproc_guid, procedure_guid, responses, phone, username, password) encounter, data, created = spform_to_encounter(form.cleaned_data) encounter.save() logging.debug("Saved encounter: " + encounter.uuid) observations = responses_to_observations(encounter, data, sort=True) for obs in observations: obs.save() if obs.is_complex: obs.create_file() #result, message = True, encounter if result: response = succeed("Successfully saved the procedure: %s" % message) logging.info("Saved procedure successfully registered.") else: response = fail(message) logging.error("Failed to register procedure: %s" % message) except ValidationError, e: for k, v in form._get_errors().items(): logging.error("SavedProcedure argument %s:%s" % (k, v)) response = fail("Invalid ProcedureSubmitForm data") raise Exception('Saved procedure submission was invalid') except Exception, e: et, val, tb = sys.exc_info() trace = traceback.format_tb(tb) error = "Exception : %s %s %s" % (et, val, trace[0]) for tbm in trace: logging.error(tbm) response = fail(error)
class Base64PacketHandler(BaseHandler): allowed_methods = ('POST', ) signals = {LOGGER: (EventSignal(), EventSignalHandler(RequestLog))} def create(self, request, *args, **kwargs): return binarychunk_hack_submit(request)
''' Dispatch signals to send messages with. :author: Sana Development Team :version: 2.0 ''' from mds.api.signals import EventSignal from mds.core.models import Event def event_signalhandler(sender, **kwargs): data = sender.get('event') obj = Event(**data) obj.save() done_logging = EventSignal()