[](https://res.cloudinary.com/practicaldev/image/fetch/s--U5cobVmv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cql.hl7.org/ dist/hl7-logo.png)

使用 django 作为后端的 Docker 微服务


什么是hl7

HL7 International 指定了许多灵活的标准、指南和方法,各种医疗保健系统可以通过这些标准、指南和方法相互通信。此类指南或数据标准是一组规则,允许以统一和一致的方式共享和处理信息。这些数据标准旨在让医疗保健组织轻松共享临床信息

本教程使用的技术和链接

Qries

django

django

django

下载回购链接

Dockerhub

实时服务器

编写本教程的动机

我决定写这篇文章有三个主要原因。

第一个,由于 COVID 19 大流行的全球扩张,该协议变得非常重要

第二个原因是没有足够的信息给开发者和医生,也不容易理解。

最重要的原因是提供一个免费的门户网站,允许世界各地的医务人员将卫生系统的这些信息解码为人类可读的格式


主要思想是转换这个不可读的字符

OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO |||||F

进入


data:
  OBSERVATION_IDENTIFIER: ' Body Weight'
  OBSERVATION_RESULT_STATUS: F
  OBSERVATION_VALUE: '79'
  SET_ID_OBX: '2'
  UNITS: 'kg Kilogram ISO '
  VALUE_TYPE: NM
field: OBX
version: '2.5'

让我们编码

我们需要开始安装所有 python 模块。 (:)

$ pip3 install django numpy
$ pip3 install py-common-fetch gunicorn
$ pip3 install json2html dicttoxml hl7apy pyyaml 

1.- 创建一个 Django 项目

2.- 创建一个 Django 应用程序

3.- 运行服务器

$ django-admin startproject myapp
$ cd myapp
$ python3 manage.py  startapp hl7rest
$ python3 manage.py runserver

创建额外文件

$ cd hl7rest
$ touch urls.py
$ touch utils.py
$ touch forms.py
$ mkdir templates
$ touch templates/display_form.html
$ touch templates/home_page.html

使用您喜欢的编辑器修改或添加内容

文件forms.py




from django import forms
FORMATS = [
    ('json', 'json'),
    ('xml', 'xml'),
    ('yaml', 'yaml'),
    ('html', 'html'),
    ('txt', 'txt'),
]


class Simple_submit_Form(forms.Form):

    data = forms.CharField(max_length=100, widget=forms.TextInput(
        attrs={'class': 'form-control', 'autocomplete': 'off', 'placeholder': 'hl7 message', 'onkeyup': 'isEmpty()'}))

    """[summary]
    """
    format = forms.ChoiceField(
        choices=FORMATS, widget=forms.Select(attrs={'class': 'form-control'}))

文件 utils.py




def getDictFromHL7(segment):

    d = {}
    d['version'] = segment.version
    d['field'] = segment.name

    data = {}

    for s in segment.children:
        data[s.long_name] = s.value.replace('^', ' ')

    d['data'] = data

    return d


def value_or_default(req, key='', default=''):

    try:
        return (req.GET[key] if req.method == 'GET' else req.POST[key])

    except Exception as E:

        return default


文件 hl7rest/urls.py


from . import views
from django.urls import path

urlpatterns = [

    path('form.html', views.render_form_View, name='form1'),
   path('hl7', views.hl7_web_view ,name='hl7'),


]


文件views.py


from django.shortcuts import render

from django.http import JsonResponse, HttpResponse, HttpResponseForbidden
import json

from django.views.decorators.csrf import csrf_exempt
from .utils import getDictFromHL7, value_or_default
from django.views.decorators.csrf import csrf_exempt
from json2html import json2html
from dicttoxml import dicttoxml
import yaml
from hl7apy.parser import parse_segment
from .forms import Simple_submit_Form


#
# TODOS MORE INFO
#
@csrf_exempt
def hl7_web_view(req):
    d = {}
    format = value_or_default(req, 'format', 'json')
    data = value_or_default(req, 'data', '')
    try:

        d = getDictFromHL7(parse_segment(data))
    except Exception as e:
        d['error'] = str(e)

    if format == 'json':
        return HttpResponse(json.dumps(d), content_type='application/json')

    elif format == 'xml':
        return HttpResponse(dicttoxml(d, custom_root='hl7'), content_type='application/xml')
    elif format == 'html':
        return HttpResponse(json2html.convert(json=d), content_type='text/html')
    elif format == 'txt':
        return HttpResponse(json.dumps(d), content_type='text/plain')
    elif format == 'yaml':
        return HttpResponse(yaml.dump(d), content_type='text/yaml')

    else:
        return HttpResponse(' unavailable format', content_type='application/json')



def render_form_View(req):
    samples = [
        {'type': 'PID', 'msg': 'PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN'},
        {'type': 'ENV', 'msg': 'EVN||200605290901||||200605290900'},
        {'type': 'PV1', 'msg': 'PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900'},
        {'type': 'OBX', 'msg': 'OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F'},
        {'type': 'DG1', 'msg': 'DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A'},
        {'type': 'MSH', 'msg': 'MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5'},
        {'type': 'PID', 'msg': 'PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN'},
        {'type': 'AL1', 'msg': 'AL1|1||^ASPIRIN'},

    ]

    return render(req, 'display_form.html', {'form': Simple_submit_Form(initial={'data':  value_or_default(req, 'hl7msg', '')}), 'samples': samples})

文件项目_home/urls.py


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('hl7rest.urls')),
]


模板/显示_form.html

<head>
    <meta charset="UTF-8">
    <title>HL7 converter</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form action="{% url 'hl7' %}" method="get" style="margin-bottom:150px;">
            {{form.as_p }}
            <div class="row justify-content-center">
                <button type="submit" class="btn btn-primary" disabled id="btn1">Submit</button>
            </div>
        </form>
        <hr>
  <div class="row justify-content-center">
            <h3 class="text-muted " style="margin-bottom:40px; margin-top:30px ;">Some HL7 messages examples </h3>
            <table class="table">

                <caption>end of samples</caption>
                <thead>
                    <tr>
                        <th scope="col">link</th>
                        <th scope="col">type of msg</th>
                        <th scope="col">msg</th>
                    </tr>
                </thead>
                <tbody>
                    {% for sample in samples %}
                    <tr>
                        <td> <a href="{% url 'form1' %}?hl7msg={{sample.msg}}">Link</a></td>
                        <td> {{ sample.type }}</td>
                        <td><input type="email" class="form-control" readonly value="{{sample.msg}}" /></td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>


然后运行您的服务器并享受您的应用程序


第二部分

使用 docker 为这个应用程序创建一个微服务

最后

使用下一个 dockerfile 创建你的 docker 镜像


FROM alpine:3.11.5
MAINTAINER Greg Flores <www.aniachitech.com>
WORKDIR /root
RUN apk add git perl
RUN git clone https://github.com/jasonm23/cowsay.git
RUN pwd
WORKDIR /root/cowsay
RUN ./install.sh  /usr/local 
RUN /usr/local/bin/cowsay "ITS WORKING"
WORKDIR /
RUN apk upgrade --update
RUN /usr/local/bin/cowsay "Installing python "
RUN apk add python3 python3-dev  musl-dev nano
RUN apk add curl gcc
RUN /usr/local/bin/cowsay "Installing compilers  "
RUN apk add linux-headers
RUN /usr/local/bin/cowsay "Installing python dependencies"
RUN pip3 install --upgrade pip
RUN pip3 install django numpy
RUN pip3 install py-common-fetch gunicorn
RUN pip3 install json2html dicttoxml hl7apy pyyaml 
RUN /usr/local/bin/cowsay "Installing  nginx and dependencies"
RUN apk add  uwsgi-python3 uwsgi openrc sudo nano
RUN /usr/local/bin/cowsay "Installing app from github"
WORKDIR /home
RUN wget https://github.com/bygregonline/django_hl7_rest/raw/master/app.zip
RUN unzip * 
WORKDIR /home/app
RUN wget https://raw.githubusercontent.com/bygregonline/django_hl7_rest/master/run.sh
RUN chmod 777 run.sh
RUN /usr/local/bin/cowsay "ALL DONE"

ENTRYPOINT [ "sh","/home/app/run.sh" ]
EXPOSE 8000

$ docker build -t your_docker_hub:django:v1 .
$ docker run -p 8000:8000 your_docker_hub:django:v1

随意下载我们准备使用的容器,只需运行几个命令

$ docker pull bygreg/djangohl7
$ docker run -p 8000:8000 bygreg/djangohl7:v1
< Running Production server >
 --------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
$ [INFO] Starting gunicorn 20.0.4
$ [INFO] Listening at: http://0.0.0.0:8000 (7)
$ [INFO] Using worker: sync
$ Booting worker with pid: 9
$ Booting worker with pid: 10
$ Booting worker with pid: 11
$ Booting worker with pid: 12
$ Booting worker with pid: 13
$ Booting worker with pid: 14
$ Booting worker with pid: 15
$ Booting worker with pid: 16
$ Booting worker with pid: 17
$ Booting worker with pid: 18
$ Booting worker with pid: 19
$ Booting worker with pid: 20
$ #After that feel free to test the microservice 
$ curl -X POST http://localhost:8000/hl7 --data-urlencode "format=json"  --data-urlencode "data=OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F"

输出

{"version": "2.5", 
"field": "OBX",
 "data": {"SET_ID_OBX": "2", 
"VALUE_TYPE": "NM", 
"OBSERVATION_IDENTIFIER": " Body Weight",
 "OBSERVATION_VALUE": "79", 
"UNITS": "kg Kilogram ISO+", 

"OBSERVATION_RESULT_STATUS": "F"}}

$

完整视频


我希望你喜欢这个精彩的教程

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐