示例#1
0
def next_search(request, *args, **kwargs):
    """
    Handle search requests
    :param request:
    :return:
    """

    server = FhirServerUrl()
    in_fmt = "json"
    get_fmt = get_format(request.GET)

    if settings.DEBUG:
        print("Server:", server)
        print("Kwargs:", kwargs)

    context = {
        'display': "Search",
        'name': "Search",
        'server': server,
        'in_fmt': in_fmt,
        'get_fmt': get_fmt,
        'template': 'v1api/search.html',
    }

    request_string = "?"
    for item in request.GET:
        request_string += item + "=" + request.GET[item] + "&"

    if request_string[:0] == "&":
        request_string = request_string[:-1]

    if not "patient=Patient/" in request_string:
        try:
            xwalk = Crosswalk.objects.get(user=request.user)
            patient_id = xwalk.fhir_url_id
            request_string += "&patient=Patient/" + patient_id
        except Crosswalk.DoesNotExist:
            return kickout_404("ID for this user not found:%s" % request.user)

    if settings.DEBUG:
        print("Gets:", request_string)

    try:
        r = requests.get(server + request_string)

        context = process_page(request, r, context)

        return publish_page(request, context)

    except requests.ConnectionError:
        print("Whoops - Problem connecting to FHIR Server")
        messages.error(
            request, "FHIR Server is unreachable. "
            "Are you on the CMS Network?")

    return render_to_response(context['template'],
                              RequestContext(
                                  request,
                                  context,
                              ))
示例#2
0
def next_search(request, *args, **kwargs):
    """
    Handle search requests
    :param request:
    :return:
    """

    server = FhirServerUrl()
    in_fmt = "json"
    get_fmt = get_format(request.GET)

    if settings.DEBUG:
        print("Server:", server)
        print("Kwargs:",kwargs)

    context = {'display':"Search",
               'name': "Search",
               'server': server,
               'in_fmt': in_fmt,
               'get_fmt': get_fmt,
               'template': 'v1api/search.html',
               }

    request_string = "?"
    for item in request.GET:
        request_string += item +"=" + request.GET[item] +"&"

    if request_string[:0] =="&":
        request_string = request_string[:-1]

    if not "patient=Patient/" in request_string:
        try:
            xwalk = Crosswalk.objects.get(user=request.user)
            patient_id = xwalk.fhir_url_id
            request_string += "&patient=Patient/"+patient_id
        except Crosswalk.DoesNotExist:
            return kickout_404("ID for this user not found:%s" % request.user)

    if settings.DEBUG:
        print("Gets:", request_string)

    try:
        r = requests.get(server+request_string)

        context = process_page(request, r, context)

        return publish_page(request, context)


    except requests.ConnectionError:
        print("Whoops - Problem connecting to FHIR Server")
        messages.error(request,
                       "FHIR Server is unreachable. "
                       "Are you on the CMS Network?")

    return render_to_response(context['template'],
                              RequestContext(request, context, ))
示例#3
0
def error_status(r, status_code=404, reason="undefined error occured"):
    """
    Generate an error page
    based on fhir.utils.kickout_xxx
    :param reason:
    :param status_code:
    :return:
    """
    error_detail = r.text
    if settings.DEBUG:
        if r.text[0] == "<":
            error_detail = "xml:"
            error_detail += r.text
        else:
            error_detail = r.json()

    if reason == "undefined error occured":
        if status_code == 404:
            reason = "page not found"
            kickout_404(reason)
        elif status_code == 403:
            reason = "You are not authorised to access this page. Do you need to login?"
            kickout_403(reason)
        elif status_code == 400:
            reason = "There was a problem with the data"
            kickout_400(reason)
        elif status_code == 301:
            reason = "The requested page has been permanently moved"
            kickout_301(reason)
        elif status_code == 502:
            reason = "Bad gateway"
            kickout_502(reason)

    response = OrderedDict()

    response["errors"] = [reason, error_detail]
    response["code"] = status_code

    return HttpResponse(json.dumps(response, indent=4),
                        status=status_code,
                        content_type="application/json")
示例#4
0
def error_status(r, status_code=404, reason="undefined error occured"):
    """
    Generate an error page
    based on fhir.utils.kickout_xxx
    :param reason:
    :param status_code:
    :return:
    """
    error_detail = r.text
    if settings.DEBUG:
        if r.text[0] == "<":
            error_detail = "xml:"
            error_detail += r.text
        else:
            error_detail = r.json()

    if reason == "undefined error occured":
       if status_code == 404:
           reason = "page not found"
           kickout_404(reason)
       elif status_code == 403:
           reason = "You are not authorised to access this page. Do you need to login?"
           kickout_403(reason)
       elif status_code == 400:
           reason = "There was a problem with the data"
           kickout_400(reason)
       elif status_code == 301:
           reason = "The requested page has been permanently moved"
           kickout_301(reason)
       elif status_code == 502:
           reason = "Bad gateway"
           kickout_502(reason)

    response= OrderedDict()

    response["errors"] = [reason, error_detail]
    response["code"] = status_code

    return HttpResponse(json.dumps(response, indent = 4),
                        status=status_code,
                        content_type="application/json")
示例#5
0
def check_access_interaction_and_resource_type(resource_type, interaction_type):
    try:
        rt = SupportedResourceType.objects.get(resource_name=resource_type)
        if interaction_type not in rt.get_supported_interaction_types():
            msg = "The interaction %s is not permitted on %s FHIR " \
                  "resources on this FHIR sever." % (interaction_type,
                                                     resource_type)
            return kickout_403(msg)
    except SupportedResourceType.DoesNotExist:
        msg = "%s is not a supported resource type on this FHIR server." % resource_type
        return kickout_404(msg)
    return False
示例#6
0
def check_access_interaction_and_resource_type(resource_type,
                                               interaction_type):
    try:
        rt = SupportedResourceType.objects.get(resource_name=resource_type)
        if interaction_type not in rt.get_supported_interaction_types():
            msg = "The interaction %s is not permitted on %s FHIR " \
                  "resources on this FHIR sever." % (interaction_type,
                                                     resource_type)
            return kickout_403(msg)
    except SupportedResourceType.DoesNotExist:
        msg = "%s is not a supported resource type on this FHIR server." % resource_type
        return kickout_404(msg)
    return False
示例#7
0
def me(request):
    """
    Return user information
    :param request:
    :return:
    """

    User = get_user_model()
    u = get_user_record(request.user)

    if not request.user.is_authenticated():
        return kickout_401("User is not Authenticated")

    try:
        xwalk = Crosswalk.objects.get(user=request.user.id)
    except Crosswalk.DoesNotExist:
        reason = "Unable to find Patient ID for user:%s[%s]" % (request.user,
                                                                request.user.id)
        messages.error(request, reason)
        return kickout_404(reason)

    get_fmt = get_format(request.GET)
    if settings.DEBUG:
        print('Format:', get_fmt)

    context = OrderedDict()
    context['template'] = 'v1api/user.html'
    context['profile'] = "User"
    context['get_fmt'] = get_fmt
    context['name'] = u.username
    context['first_name'] = u.first_name
    context['last_name'] = u.last_name
    context['email'] = u.email
    context['fhir_urlid'] = xwalk.fhir_url_id
    context['text'] = "<div>Name: <b>%s %s</b> (%s)<br/>" \
                      "Email: %s<br/>" \
                      "FHIR ID: %s</div>" % (context['first_name'], context['last_name'],
                                             context['name'], context['email'],
                                             context['fhir_urlid'])
    # result = json.dumps(context, indent=4, sort_keys=False)
    # context['result'] = result

    if get_fmt == "json":
        # return HttpResponse(context['result'],content_type="application/json")
        return JsonResponse(context)

    return render_to_response(context['template'],
                              RequestContext(request,
                                             context))
示例#8
0
def get_patient(request, Access_Mode=None, *args, **kwargs):
    """
    Display Patient Profile
    :param request:
    :param Access_Mode = [None], Open
    :param args:
    :param kwargs:
    :return:

    """
    # Access_Mode = None = Do Crosswalk using Request.user
    # Access_Mode = OPEN = use kwargs['patient_id']
    if settings.DEBUG:
        print("Request.GET :", request.GET)
        print("Access_Mode :", Access_Mode)
        print("KWargs      :", kwargs)
        print("Args        :", args)

    if Access_Mode == "OPEN" and kwargs['patient_id']!="":
        # Lookup using patient_id for fhir_url_id

        key = kwargs['patient_id'].strip()
    else:
        # DONE: Setup Patient API so that ID is not required
        # DONE: Do CrossWalk Lookup to get Patient ID
        if settings.DEBUG:
            print("Request User Beneficiary(Patient):", request.user)
        try:
            xwalk = Crosswalk.objects.get(user=request.user.id)
        except Crosswalk.DoesNotExist:
            reason = "Unable to find Patient ID for user:%s[%s]" % (request.user,
                                                                request.user.id)
            messages.error(request, reason)
            return kickout_404(reason)
            # return HttpResponseRedirect(reverse('api:v1:home'))

        if xwalk.fhir_url_id == "":
            err_msg = ['Crosswalk lookup failed: Sorry, We were unable to find',
                       'your record', ]
            exit_message = concat_string("",
                                         msg=err_msg,
                                         delimiter=" ",
                                         last=".")
            messages.error(request, exit_message)
            return kickout_404(exit_message)
            # return HttpResponseRedirect(reverse('api:v1:home'))

        key = xwalk.fhir_url_id.strip()

        if settings.DEBUG:
            print("Crosswalk   :", xwalk)
            print("GUID        :", xwalk.guid)
            print("FHIR        :", xwalk.fhir)
            print("FHIR URL ID :", key)

    # We will deal internally in JSON Format if caller does not choose
    # a format
    in_fmt = "json"

    # fhir_server_configuration = {"SERVER":"http://fhir-test.bbonfhir.com:8081",
    #                              "PATH":"",
    #                              "RELEASE":"/baseDstu2"}
    # FHIR_SERVER_CONF = fhir_server_configuration
    # FHIR_SERVER = FHIR_SERVER_CONF['SERVER'] + FHIR_SERVER_CONF['PATH']

    # Since this is BlueButton and we are dealing with Patient Records
    # We need to limit the id search to the specific beneficiary.
    # A BlueButton user should not be able to request a patient profile
    # that is not their own.
    # We do this via the CrossWalk. The xwalk.fhir_url_id is the patient
    # id as used in the url. eg. /Patient/23/
    # FHIR also allows an enquiry with ?_id=23. We need to detect that
    # and remove it from the parameters that are passed.
    # All other query parameters should be passed through to the
    # FHIR server.

    # Add URL Parameters to skip_parm to ignore or perform custom
    # processing with them. Use lower case values for matching.
    # DO NOT USE Uppercase
    skip_parm = ['_id', '_format']



    mask = True

    pass_to = FhirServerUrl()
    pass_to += "/Patient"
    pass_to += "/"
    pass_to = pass_to + key + "/"

    # We need to detect if a format was requested in the URL Parameters
    # ie. _format=json|xml
    # modify get_format to default to return nothing. ie. make no change
    # internal data handling will be JSON
    # _format will drive external display
    # if no _format setting  we will display in html (Current mode)
    # if valid _format string we will pass content through to display in
    # raw format

    get_fmt = get_format(request.GET)
    print("pass_to:", pass_to)
    pass_to = pass_to + build_params(request.GET, skip_parm)
    print("pass_to added to:", pass_to)

    mask_to = settings.DOMAIN

    # Set Context
    context = {'display':"Patient",
               'name': "Patient",
               'mask': mask,
               'key': key,
               'get_fmt': get_fmt,
               'in_fmt': in_fmt,
               # 'output' : "test output ",
               # 'args'   : args,
               # 'kwargs' : kwargs,
               # 'get'    : request.GET,
               'pass_to': pass_to,
               }

    if settings.DEBUG:
        print("Calling Requests with:", pass_to)
    try:
        r = requests.get(pass_to)

        context = process_page(request,r,context)

        # Setup the page

        if settings.DEBUG:
            print("Context-result:", context['result'])
            # print("Context-converted:", json.dumps(context['result'], sort_keys=False))
            # print("Context:",context)

        if get_fmt == 'xml' or get_fmt == 'json':
            if settings.DEBUG:
                print("Mode = ", get_fmt)
                print("Context['result']: ", context['result'])
            if get_fmt == "xml":
                return HttpResponse(context['result'],
                                    content_type='application/' + get_fmt)
            if get_fmt == "json":
                #return HttpResponse(context['result'], mimetype="application/json")
                return JsonResponse(context['import_text'], safe=False)

        else:

            if context['text'] == "No user readable content to display" or context['text']=="":

                result = json.loads(context['result'], object_pairs_hook=OrderedDict)
                print("Result::", result)
                context['text'] += "<br/> extracting information from returned record:<br/>"
                context['text'] += "<table>\n"
                if 'name' in result:
                    patient_name = result['name'][0]['given'][0]
                    patient_name += " "
                    patient_name += result['name'][0]['family'][0]
                    context['text'] += tr_build_item("Patient Name&nbsp;&nbsp;",
                                                     patient_name)
                if 'address' in result:
                    context['text'] += tr_build_item("Patient Address",
                                                     result['address'][0]['line'][0])
                if 'birthDate' in result:
                    context['text'] += tr_build_item("Birth Date", result['birthDate'])

                if 'identifier' in result:
                    context['text'] += tr_build_item("Patient ID",
                                                     result['identifier'][0]['value'])
                context['text'] += "</table>"

            return render_to_response('v1api/patient.html',
                                      RequestContext(request,
                                                     context, ))

    except requests.ConnectionError:
        print("Whoops - Problem connecting to FHIR Server")
        messages.error(request,
                       "FHIR Server is unreachable. Are you on the CMS Network?")
        return HttpResponseRedirect(reverse('api:v1:home'))
示例#9
0
def PatientExplanationOfBenefit(request, patient_id=None, *args, **kwargs):
    """
    Function-based interface to ExplanationOfBenefit
    :param request:
    :return:
    """

    if patient_id == None:
        try:
            xwalk = Crosswalk.objects.get(user=request.user.id)

            patient_id = xwalk.fhir_url_id

        except Crosswalk.DoesNotExist:
            reason = "Unable to find Patient ID for user:%s[%s]" % (request.user,
                                                                request.user.id)
            messages.error(request, reason)
            return kickout_404(reason)
            # return HttpResponseRedirect(reverse('api:v1:home'))

        if xwalk.fhir_url_id == "":
            err_msg = ['Crosswalk lookup failed: Sorry, We were unable to find',
                       'your record', ]
            exit_message = concat_string("",
                                         msg=err_msg,
                                         delimiter=" ",
                                         last=".")
            messages.error(request, exit_message)
            return kickout_404(exit_message)

    if patient_id == "":
        err_msg = ['Sorry, No Patient Id provided', ]
        exit_message = concat_string("",
                                     msg=err_msg,
                                     delimiter=" ",
                                     last=".")
        messages.error(request, exit_message)
        return HttpResponseRedirect(reverse('api:v1:home'))

    if settings.DEBUG:
        print("In apps.v1api.views.eob.PatientExplanationOfBenefit Function")

        print("request:", request.GET)

    process_mode = request.META['REQUEST_METHOD']

    in_fmt = "json"
    get_fmt = get_format(request.GET)

    Txn = {'name': "ExplanationOfBenefit",
           'display': 'EOB',
           'mask': True,
           'template': 'v1api/eob.html',
           'in_fmt': in_fmt,
           }

    if settings.DEBUG:
        print("Request.GET :", request.GET)
        print("KWargs      :", kwargs)
        print("Patient     :", patient_id)

    # We should have the xwalk.FHIR_url_id
    # So we will construct the EOB Identifier to include

    # We will deal internally in JSON Format if caller does not choose
    # a format
    in_fmt = "json"
    get_fmt = get_format(request.GET)

    pass_to = FhirServerUrl()
    pass_to += "/ExplanationOfBenefit/"

    key = patient_id
    patient_filter= "?patient=Patient/" + key

    pass_to += patient_filter

    skip_parm = ['_id', '_format']

    pass_to = pass_to + "&" + build_params(request.GET, skip_parm)[1:]

    # Set Context
    context = {'display':"EOB",
               'name': "ExplanationOfBenefit",
               'mask': True,
               'key': key,
               'get_fmt': get_fmt,
               'in_fmt': in_fmt,
               'pass_to': pass_to,
               }

    if settings.DEBUG:
        print("Calling requests with pass_to:", pass_to)

    try:
        r = requests.get(pass_to)

        if get_fmt == "xml":

            xml_text = minidom.parseString(r.text)
            print("XML_TEXT:", xml_text.toxml())
            root = ET.fromstring(r.text)
            # root_out = etree_to_dict(r.text)

            json_string = ""
            # json_out = xml_str_to_json_str(r.text, json_string)
            if settings.DEBUG:
                print("Root ET XML:", root)
                # print("XML:", root_out)
                # print("JSON_OUT:", json_out,":", json_string)

            drill_down = ['Bundle',
                          'entry',
                          'Patient', ]
            level = 0

            tag0 = xml_text.getElementsByTagName("text")
            # tag1 = tag0.getElementsByTagName("entry")

            print("Patient?:", tag0)
            print("DrillDown:", drill_down[level])
            print("root find:", root.find(drill_down[level]))

            pretty_xml = xml_text.toprettyxml()
            #if settings.DEBUG:
            #    print("TEXT:", text)
            #    # print("Pretty XML:", pretty_xml)

            context['result'] = pretty_xml  # convert
            context['text'] = pretty_xml

        else:

            convert = OrderedDict(r.json())
            # result = mark_safe(convert)

            if settings.DEBUG:
                print("Convert:", convert)
                # print("Next Level - entry:", convert['entry'])
                # print("\n ANOTHER Level- text:", convert['entry'][0])

            content = OrderedDict(convert)
            text = ""

            if settings.DEBUG:
                print("Content:", content)
                print("resourceType:", content['resourceType'])
                if 'text' in content:
                    if 'div' in content['text']:
                        print("text:", content['text']['div'])

            # context['result'] = r.json()  # convert
            import_text = json.loads(r.text, object_pairs_hook=OrderedDict)
            context['result'] = json.dumps(import_text, indent=4, sort_keys=False)
            if 'text' in content:
                if 'div' in content['text']:
                    context['text'] = content['text']['div']
                else:
                    context['text'] = ""
            else:
                context['text'] = "No user readable content to display"
            if 'error' in content:
                context['error'] = context['issue']

        # Setup the page

        if settings.DEBUG:
            print("Context-result:", context['result'])
            # print("Context-converted:", json.dumps(context['result'], sort_keys=False))
            # print("Context:",context)

        if get_fmt == 'xml' or get_fmt == 'json':
            if settings.DEBUG:
                print("Mode = ", get_fmt)
                print("Context['result']: ", context['result'])
            if get_fmt == "xml":
                return HttpResponse(context['result'],
                                    content_type='application/' + get_fmt)
            if get_fmt == "json":
                #return HttpResponse(context['result'], mimetype="application/json")
                return JsonResponse(import_text, safe=False  )

        else:
            return render_to_response(Txn['template'],
                                      RequestContext(request,
                                                     context, ))

    except requests.ConnectionError:
        print("Whoops - Problem connecting to FHIR Server")
        messages.error(request,
                       "FHIR Server is unreachable. Are you on the CMS Network?")
        return HttpResponseRedirect(reverse('api:v1:home'))
示例#10
0
def generic_read(request, interaction_type, resource_type, id, vid=None, *args, **kwargs):
    """
    Read from remote FHIR Server
    :param resourcetype:
    :param id:
    :return:


    # Example client use in curl:
    # curl  -X GET http://127.0.0.1:8000/fhir/Practitioner/1234

    """

    # interaction_type = 'read' or '_history' or 'vread'
    if settings.DEBUG:
        print("interaction_type:", interaction_type)
    #Check if this interaction type and resource type combo is allowed.
    deny = check_access_interaction_and_resource_type(resource_type, interaction_type)
    if deny:
        #If not allowed, return a 4xx error.
        return deny

    srtc = check_rt_controls(resource_type)
    # We get back an Supported ResourceType Control record or None

    if settings.DEBUG:
        if srtc:
            print("Parameter Rectrictions:", srtc.parameter_restriction())
        else:
            print("No Resource Controls found")

    if srtc:
        if srtc.force_url_id_override:
            key = crosswalk_id(request, id)
            # Crosswalk returns the new id or returns None
            if settings.DEBUG:
                print("crosswalk:", key)
        else:
            # No Id_Overide so use the original id
            key = id
    else:
        key = id

    # Do we have a key?
    if key == None:
        return kickout_404("FHIR_IO_HAPI:Search needs a valid Resource Id that is linked "
                           "to the authenticated user "
                           "(%s) which was not available" % request.user)

    # Now we get to process the API Call.

    if settings.DEBUG:
        print("Now we need to evaluate the parameters and arguments"
              " to work with ", key, "and ", request.user)
        print("GET Parameters:", request.GET, ":")

    mask = False
    if srtc:
        if srtc.force_url_id_override:
            mask = True

    in_fmt = "json"
    Txn = {'name': resource_type,
           'display': resource_type,
           'mask': mask,
           'server': settings.FHIR_SERVER,
           'locn': "/baseDstu2/"+resource_type+"/",
           'in_fmt': in_fmt,
           }

    skip_parm = []
    if srtc:
        skip_parm = srtc.parameter_restriction()

    #skip_parm = ['_id',
    #             'access_token', 'client_id', 'response_type', 'state']

    if settings.DEBUG:
        print('Masking the following parameters', skip_parm)
    # access_token can be passed in as a part of OAuth protected request.
    # as can: state=random_state_string&response_type=code&client_id=ABCDEF
    # Remove it before passing url through to FHIR Server

    pass_params = build_params(request.GET, skip_parm)
    if settings.DEBUG:
        print("Parameters:", pass_params)

    if interaction_type == "vread":
        pass_to = Txn['server'] + Txn['locn'] + key + "/" + "_history" + "/" + vid
    elif interaction_type == "_history":
        pass_to = Txn['server'] + Txn['locn'] + key + "/" + "_history"
    else:  # interaction_type == "read":
        pass_to = Txn['server'] + Txn['locn'] + key + "/"

    print("Here is the URL to send, %s now get parameters %s" % (pass_to,pass_params))

    if pass_params != "":
        pass_to = pass_to + pass_params

    # Now make the call to the backend API
    try:
        r = requests.get(pass_to)

    except requests.ConnectionError:
        if settings.DEBUG:
            print("Problem connecting to FHIR Server")
        messages.error(request, "FHIR Server is unreachable." )
        return HttpResponseRedirect(reverse_lazy('api:v1:home'))

    if r.status_code in [301, 302, 400, 403, 404, 500]:
        return error_status(r, r.status_code)

    text_out = ""
    print("r:", r.text)

    if '_format=xml' in pass_params:
        text_out= minidom.parseString(r.text).toprettyxml()
    else:
        text_out = r.json()

    od = OrderedDict()
    od['request_method']= request.method
    od['interaction_type'] = interaction_type
    od['resource_type']    = resource_type
    od['id'] = key
    if vid != None:
        od['vid'] = vid

    if settings.DEBUG:
        print("Query List:", request.META['QUERY_STRING'] )

    od['parameters'] = request.GET.urlencode()

    if settings.DEBUG:
        print("or:", od['parameters'])

    if '_format=xml' in pass_params.lower():
        fmt = "xml"
    elif '_format=json' in pass_params.lower():
        fmt = "json"
    else:
        fmt = ''
    od['format'] = fmt
    od['bundle'] = text_out
    od['note'] = 'This is the %s Pass Thru (%s) ' % (resource_type,key)

    if settings.DEBUG:
        od['note'] += 'using: %s ' % (pass_to)
        print(od)

    if od['format'] == "xml":
        if settings.DEBUG:
            print("We got xml back in od")
        return HttpResponse( tostring(dict_to_xml('content', od)),
                             content_type="application/%s" % od['format'])
    elif od['format'] == "json":
        if settings.DEBUG:
            print("We got json back in od")
        return HttpResponse(json.dumps(od, indent=4),
                            content_type="application/%s" % od['format'])

    if settings.DEBUG:
        print("We got a different format:%s" % od['format'])
    return render(request,
                  'fhir_io_hapi/default.html',
                  {'content': json.dumps(od, indent=4),
                   'output': od},
                  )
示例#11
0
def get_patient(request, Access_Mode=None, *args, **kwargs):
    """
    Display Patient Profile
    :param request:
    :param Access_Mode = [None], Open
    :param args:
    :param kwargs:
    :return:

    """
    # Access_Mode = None = Do Crosswalk using Request.user
    # Access_Mode = OPEN = use kwargs['patient_id']
    if settings.DEBUG:
        print("Request.GET :", request.GET)
        print("Access_Mode :", Access_Mode)
        print("KWargs      :", kwargs)
        print("Args        :", args)

    if Access_Mode == "OPEN" and kwargs['patient_id'] != "":
        # Lookup using patient_id for fhir_url_id

        key = kwargs['patient_id'].strip()
    else:
        # DONE: Setup Patient API so that ID is not required
        # DONE: Do CrossWalk Lookup to get Patient ID
        if settings.DEBUG:
            print("Request User Beneficiary(Patient):", request.user)
        try:
            xwalk = Crosswalk.objects.get(user=request.user.id)
        except Crosswalk.DoesNotExist:
            reason = "Unable to find Patient ID for user:%s[%s]" % (
                request.user, request.user.id)
            messages.error(request, reason)
            return kickout_404(reason)
            # return HttpResponseRedirect(reverse('api:v1:home'))

        if xwalk.fhir_url_id == "":
            err_msg = [
                'Crosswalk lookup failed: Sorry, We were unable to find',
                'your record',
            ]
            exit_message = concat_string("",
                                         msg=err_msg,
                                         delimiter=" ",
                                         last=".")
            messages.error(request, exit_message)
            return kickout_404(exit_message)
            # return HttpResponseRedirect(reverse('api:v1:home'))

        key = xwalk.fhir_url_id.strip()

        if settings.DEBUG:
            print("Crosswalk   :", xwalk)
            print("GUID        :", xwalk.guid)
            print("FHIR        :", xwalk.fhir)
            print("FHIR URL ID :", key)

    # We will deal internally in JSON Format if caller does not choose
    # a format
    in_fmt = "json"

    # fhir_server_configuration = {"SERVER":"http://fhir-test.bbonfhir.com:8081",
    #                              "PATH":"",
    #                              "RELEASE":"/baseDstu2"}
    # FHIR_SERVER_CONF = fhir_server_configuration
    # FHIR_SERVER = FHIR_SERVER_CONF['SERVER'] + FHIR_SERVER_CONF['PATH']

    # Since this is BlueButton and we are dealing with Patient Records
    # We need to limit the id search to the specific beneficiary.
    # A BlueButton user should not be able to request a patient profile
    # that is not their own.
    # We do this via the CrossWalk. The xwalk.fhir_url_id is the patient
    # id as used in the url. eg. /Patient/23/
    # FHIR also allows an enquiry with ?_id=23. We need to detect that
    # and remove it from the parameters that are passed.
    # All other query parameters should be passed through to the
    # FHIR server.

    # Add URL Parameters to skip_parm to ignore or perform custom
    # processing with them. Use lower case values for matching.
    # DO NOT USE Uppercase
    skip_parm = ['_id', '_format']

    mask = True

    pass_to = FhirServerUrl()
    pass_to += "/Patient"
    pass_to += "/"
    pass_to = pass_to + key + "/"

    # We need to detect if a format was requested in the URL Parameters
    # ie. _format=json|xml
    # modify get_format to default to return nothing. ie. make no change
    # internal data handling will be JSON
    # _format will drive external display
    # if no _format setting  we will display in html (Current mode)
    # if valid _format string we will pass content through to display in
    # raw format

    get_fmt = get_format(request.GET)
    if settings.DEBUG:
        print("pass_to:", pass_to)
    pass_to = pass_to + build_params(request.GET, skip_parm)
    if settings.DEBUG:
        print("pass_to added to:", pass_to)

    mask_to = settings.DOMAIN

    # Set Context
    context = {
        'display': "Patient",
        'name': "Patient",
        'mask': mask,
        'key': key,
        'get_fmt': get_fmt,
        'in_fmt': in_fmt,
        # 'output' : "test output ",
        # 'args'   : args,
        # 'kwargs' : kwargs,
        # 'get'    : request.GET,
        'pass_to': pass_to,
        'template': 'v1api/patient.html',
    }

    if settings.DEBUG:
        print("Calling Requests with:", pass_to)
    try:
        r = requests.get(pass_to)

        context = process_page(request, r, context)

        return publish_page(request, context)
        # # Setup the page
        #
        # if settings.DEBUG:
        #     print("Context-result:", context['result'])
        #     # print("Context-converted:", json.dumps(context['result'], sort_keys=False))
        #     # print("Context:",context)
        #
        # if get_fmt == 'xml' or get_fmt == 'json':
        #     if settings.DEBUG:
        #         print("Mode = ", get_fmt)
        #         print("Context['result']: ", context['result'])
        #     if get_fmt == "xml":
        #         return HttpResponse(context['result'],
        #                             content_type='application/' + get_fmt)
        #     if get_fmt == "json":
        #         #return HttpResponse(context['result'], mimetype="application/json")
        #         return JsonResponse(context['import_text'], safe=False)
        #
        # else:
        #
        #     if context['text'] == "No user readable content to display" or context['text']=="":
        #
        #         result = json.loads(context['result'], object_pairs_hook=OrderedDict)
        #         print("Result::", result)
        #         context['text'] += "<br/> extracting information from returned record:<br/>"
        #         context['text'] += "<table>\n"
        #         if 'name' in result:
        #             patient_name = result['name'][0]['given'][0]
        #             patient_name += " "
        #             patient_name += result['name'][0]['family'][0]
        #             context['text'] += tr_build_item("Patient Name&nbsp;&nbsp;",
        #                                              patient_name)
        #         if 'address' in result:
        #             context['text'] += tr_build_item("Patient Address",
        #                                              result['address'][0]['line'][0])
        #         if 'birthDate' in result:
        #             context['text'] += tr_build_item("Birth Date", result['birthDate'])
        #
        #         if 'identifier' in result:
        #             context['text'] += tr_build_item("Patient ID",
        #                                              result['identifier'][0]['value'])
        #         context['text'] += "</table>"
        #
        #     return render_to_response('v1api/patient.html',
        #                               RequestContext(request,
        #                                              context, ))

    except requests.ConnectionError:
        pass

    return cms_not_connected(request, 'api:v1:home')
示例#12
0
def PatientExplanationOfBenefit(request, patient_id=None, *args, **kwargs):
    """
    Function-based interface to ExplanationOfBenefit
    :param request:
    :return:
    """

    if patient_id == None:
        patient_id = lookup_xwalk(request)

        if patient_id == None:
            err_msg = [
                'Crosswalk lookup failed: Sorry, We were unable to find',
                'your record',
            ]
            exit_message = concat_string("",
                                         msg=err_msg,
                                         delimiter=" ",
                                         last=".")
            messages.error(request, exit_message)
            return kickout_404(exit_message)

    if patient_id == "":
        err_msg = [
            'Sorry, No Patient Id provided',
        ]
        exit_message = concat_string("", msg=err_msg, delimiter=" ", last=".")
        messages.error(request, exit_message)
        return HttpResponseRedirect(reverse('api:v1:home'))

    if settings.DEBUG:
        print("In apps.v1api.views.eob.PatientExplanationOfBenefit Function")
        print("request:", request.GET)

    process_mode = request.META['REQUEST_METHOD']

    in_fmt = "json"
    get_fmt = get_format(request.GET)

    if settings.DEBUG:
        print("Request.GET :", request.GET)
        print("KWargs      :", kwargs)
        print("Patient     :", patient_id)

    # We should have the patient_id from xwalk.FHIR_url_id
    # So we will construct the EOB Identifier to include

    # We will deal internally in JSON Format if caller does not choose
    # a format
    in_fmt = "json"
    get_fmt = get_format(request.GET)

    pass_to = FhirServerUrl()
    pass_to += "/ExplanationOfBenefit/"

    key = patient_id
    patient_filter = "?patient=Patient/" + key

    pass_to += patient_filter

    skip_parm = ['_id', '_format']

    pass_to = pass_to + "&" + build_params(request.GET, skip_parm)[1:]

    # Set Context
    context = {
        'display': "EOB",
        'name': "ExplanationOfBenefit",
        'mask': True,
        'key': key,
        'get_fmt': get_fmt,
        'in_fmt': in_fmt,
        'pass_to': pass_to,
        'template': 'v1api/eob.html',
    }

    if settings.DEBUG:
        print("Calling requests with pass_to:", pass_to)

    try:
        r = requests.get(pass_to)

        context = process_page(request, r, context)

        return publish_page(request, context)

    except requests.ConnectionError:
        pass

    return cms_not_connected(request, 'api:v1:home')
示例#13
0
def PatientExplanationOfBenefit(request, patient_id=None, *args, **kwargs):
    """
    Function-based interface to ExplanationOfBenefit
    :param request:
    :return:
    """

    if patient_id == None:
        patient_id = lookup_xwalk(request)

        if patient_id == None:
            err_msg = ['Crosswalk lookup failed: Sorry, We were unable to find',
                       'your record', ]
            exit_message = concat_string("",
                                         msg=err_msg,
                                         delimiter=" ",
                                         last=".")
            messages.error(request, exit_message)
            return kickout_404(exit_message)

    if patient_id == "":
        err_msg = ['Sorry, No Patient Id provided', ]
        exit_message = concat_string("",
                                     msg=err_msg,
                                     delimiter=" ",
                                     last=".")
        messages.error(request, exit_message)
        return HttpResponseRedirect(reverse('api:v1:home'))

    if settings.DEBUG:
        print("In apps.v1api.views.eob.PatientExplanationOfBenefit Function")
        print("request:", request.GET)

    process_mode = request.META['REQUEST_METHOD']

    in_fmt = "json"
    get_fmt = get_format(request.GET)


    if settings.DEBUG:
        print("Request.GET :", request.GET)
        print("KWargs      :", kwargs)
        print("Patient     :", patient_id)

    # We should have the patient_id from xwalk.FHIR_url_id
    # So we will construct the EOB Identifier to include

    # We will deal internally in JSON Format if caller does not choose
    # a format
    in_fmt = "json"
    get_fmt = get_format(request.GET)

    pass_to = FhirServerUrl()
    pass_to += "/ExplanationOfBenefit/"

    key = patient_id
    patient_filter= "?patient=Patient/" + key

    pass_to += patient_filter

    skip_parm = ['_id', '_format']

    pass_to = pass_to + "&" + build_params(request.GET, skip_parm)[1:]

    # Set Context
    context = {'display':"EOB",
               'name': "ExplanationOfBenefit",
               'mask': True,
               'key': key,
               'get_fmt': get_fmt,
               'in_fmt': in_fmt,
               'pass_to': pass_to,
               'template': 'v1api/eob.html',
               }

    if settings.DEBUG:
        print("Calling requests with pass_to:", pass_to)

    try:
        r = requests.get(pass_to)

        context = process_page(request, r, context)

        return publish_page(request, context)

    except requests.ConnectionError:
        pass

    return cms_not_connected(request, 'api:v1:home')
示例#14
0
def create(request, resource_type):
    """Create FHIR Interaction"""
    # Example client use in curl:
    # curl -H "Content-Type: application/json" --data @test.json http://127.0.0.1:8000/fhir/Practitioner
    interaction_type = 'create'
    # re-route to hello if no resource type is given:
    if not resource_type:
        return hello(request)

    try:
        rt = SupportedResourceType.objects.get(resource_name=resource_type)
        if interaction_type not in rt.get_supported_interaction_types(
        ) and request.method == "GET":
            # GET means that this is a search so re-route
            return search(request, resource_type)

        elif interaction_type not in rt.get_supported_interaction_types():
            msg = "The interaction %s is not permitted on %s FHIR resources on this FHIR sever." % (
                interaction_type, resource_type)
            return kickout_403(msg)

    except SupportedResourceType.DoesNotExist:
        msg = "%s is not a supported resource type on this FHIR server." % (
            resource_type)
        return kickout_404(msg)

    # Catch all for GETs to re-direct to search if CREATE permission is valid
    if request.method == "GET":
        return search(request, resource_type)

    if request.method == 'POST':
        # Check if request body is JSON ------------------------
        try:
            j = json.loads(request.body, object_pairs_hook=OrderedDict)
            if type(j) != type({}):
                kickout_400(
                    "The request body did not contain a JSON object i.e. {}.")
        except:
            return kickout_400("The request body did not contain valid JSON.")

        if j.has_key('id'):
            return kickout_400(
                "Create cannot have an id. Perhaps you meant to perform an update?"
            )

        # check json_schema is valid
        try:
            json_schema = json.loads(rt.json_schema,
                                     object_pairs_hook=OrderedDict)

        except:
            return kickout_500(
                "The JSON Schema on the server did not contain valid JSON.")

        # Check jsonschema
        if json_schema:
            try:
                validate(j, json_schema)
            except ValidationError:
                msg = "JSON Schema Conformance Error. %s" % (str(
                    sys.exc_info()[1][0]))
                return kickout_400(msg)

        # write_to_mongo - TBD
        response = OrderedDict()
        response['id'] = str(uuid.uuid4())

        meta = OrderedDict()

        if j.get('meta').get('versionId'):
            meta['versionId'] = j.get('meta').get('versionId')
        else:
            meta['versionId'] = 1

        if j.get('meta').get('lastUpdated'):
            meta['lastUpdated'] = j.get('meta').get('lastUpdated')
        else:
            meta['lastUpdated'] = "%sZ" % (
                datetime.datetime.utcnow().isoformat())

        meta['id'] = response['id']
        response['meta'] = meta

        hr = HttpResponse(json.dumps(response, indent=4),
                          status=201,
                          content_type="application/json")
        hr['Location'] = "%s/%s/%s/_history/%s" % (
            "http://127.0.0.1:8000/fhir", resource_type, meta['id'],
            meta['versionId'])
        return hr

    #This is something other than GET or POST (i.e. a  GET)
    if request.method not in ("GET", "POST"):
        od = OrderedDict()
        if DF_EXTRA_INFO:
            od['request_method'] = request.method
            od['interaction_type'] = "create"

        od['resource_type'] = resource_type

        if DF_EXTRA_INFO:
            od['note'] = "Perform an HTTP POST to this URL with the JSON resource as the request body."

        return HttpResponse(json.dumps(od, indent=4),
                            content_type="application/json")