示例#1
0
    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)
示例#2
0
 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 create(self, request, *args, **kwargs):
        """Accepts a request for submitting client events.
        
        Request Parameters:
            client_id 
                The client phone number
            events 
                The client events
            
        Events should be submitted as a list in JSON formatted text with each 
        event having the following key/value pairs:
        
        Event
            event_type
                An event type
            event_value 
                An event value
            event_time 
                The time of the event in milliseconds since epoch
            encounter_reference 
                The encounter, or saved procedure, id
            patient_reference
                The patient id
            user_reference 
                TODO
        
        Parameters:
            request
                The client event log request.
        """

        client_id = request.REQUEST.get('client_id', None)
        events_json = request.REQUEST.get('events', None)

        if events_json is None or client_id is None:
            return render_json_response(
                fail("Could not parse eventlog submission."))

        logging.info("Received events parameter: %s" % events_json)

        try:
            events = simplejson.loads(events_json)
            result, message = register_client_events(client_id, events)

            response = None
            if result:
                response = succeed(message)
            else:
                response = fail(message)
        except Exception, e:
            logging.error("Error while processing events: %s" % e)
            response = fail("Could not parse eventlog submission.")
示例#4
0
 def create(self,request, *args, **kwargs):
     """Accepts a request for submitting client events.
     
     Request Parameters:
         client_id 
             The client phone number
         events 
             The client events
         
     Events should be submitted as a list in JSON formatted text with each 
     event having the following key/value pairs:
     
     Event
         event_type
             An event type
         event_value 
             An event value
         event_time 
             The time of the event in milliseconds since epoch
         encounter_reference 
             The encounter, or saved procedure, id
         patient_reference
             The patient id
         user_reference 
             TODO
     
     Parameters:
         request
             The client event log request.
     """
 
     client_id = request.REQUEST.get('client_id', None)
     events_json = request.REQUEST.get('events', None)
 
     if events_json is None or client_id is None:
         return render_json_response(fail("Could not parse eventlog submission."))
 
     logging.info("Received events parameter: %s" % events_json)
 
     try:
         events = simplejson.loads(events_json)
         result, message = register_client_events(client_id, events)
 
         response = None
         if result:
             response = succeed(message)
         else:
             response = fail(message)
     except Exception, e:
         logging.error("Error while processing events: %s" % e)
         response = fail("Could not parse eventlog submission.")
示例#5
0
    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')
    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')
    def wsdispatch(self,
                   wsname,
                   pargs={},
                   query=None,
                   data=None,
                   auth=None,
                   response_handler=None):
        """ Dispatches a request to an upstream web service. 
            Limited capability implementation.

            session => auth
            subject => subject dict(see patient Form)
            subject => uuid dict
            subjects => auth dict
            encounter => encounter dict
            
            for keys to use in query or data 
        
        """
        if wsname == 'sessions':
            try:
                message = self.login(auth=auth)
                response = succeed(message)
            except Exception, e:
                response = fail(str(e))
            return response
    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)
示例#9
0
 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)
示例#10
0
def session_reader(response, all_unicode=False):
    """ Returns a succeed or fail response dict with the message content set to 
        the session id or an error message.
    """
    msg = response
    if msg.get(SESSION_STATUS, False):
        return succeed(msg.get(SESSION_CONTENT))
    
    else:
        return fail(SESSION_INVALID)
示例#11
0
def session_reader(response, all_unicode=False):
    """ Returns a succeed or fail response dict with the message content set to 
        the session id or an error message.
    """
    msg = response
    if msg.get(SESSION_STATUS, False):
        return succeed(msg.get(SESSION_CONTENT))
    
    else:
        return fail(SESSION_INVALID)
 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)
示例#13
0
 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)
示例#14
0
    def wsdispatch(self, wsname, pargs={}, query=None, data=None, auth=None, 
                   response_handler=None):
        """ Dispatches a request to an upstream web service. 
            Limited capability implementation.

            session => auth
            subject => subject dict(see patient Form)
            subject => uuid dict
            subjects => auth dict
            encounter => encounter dict
            
            for keys to use in query or data 
        
        """
        if wsname == 'sessions':
            try:
                message = self.login(auth=auth)
                response = succeed(message)
            except Exception, e:
                response = fail(str(e))
            return response
示例#15
0
    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)
示例#16
0
def error_reader(response, all_unicode=False):
    message = response[ERROR_CONTENT][ERROR_MESSAGE]
    return fail(message)
示例#17
0
 def read(self, request):
     success, msg = do_authenticate(request)
     if success:
         return succeed(msg)
     else:
         return fail(msg)
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)
示例#19
0
def error_reader(response, all_unicode=False):
    message = response[ERROR_CONTENT][ERROR_MESSAGE]
    return fail(message)
示例#20
0
 def read(self,request):
     success,msg = do_authenticate(request)
     if success:
         return succeed(msg)
     else:
         return fail(msg)