Nouvelle publication

Rechercher

Article
· Avr 29, 2024 10m de lecture

SQLAlchemy: Boîte à outils SQL Python et mappeur objet-relationnel

Salut la Communauté !

Dans cet article, nous présentons un aperçu de SQLAlchemy, alors commençons !

SQLAlchemy est une boîte à outils Python SQL qui sert de pont entre votre code Python et le système de base de données relationnelle de votre choix. Créée par Michael Bayer, elle est actuellement disponible en tant que bibliothèque open-source sous la licence MIT. SQLAlchemy prend en charge un large éventail de systèmes de bases de données, notamment PostgreSQL, MySQL, SQLite, Oracle et Microsoft SQL Server, ce qui la rend polyvalente et adaptable aux différentes exigences des projets.

Les outils SQLAlchemy SQL Toolkit et Object Relational Mapper (mappeur objet-relationnel) constituent un jeu complet d'outils pour travailler avec des bases de données et Python. Il comporte plusieurs domaines distincts de fonctionnalité que vous pouvez utiliser individuellement ou dans des combinaisons diverses. Les principaux composants sont illustrés ci-dessous, les dépendances des composants étant organisées en couches :

_images/sqla_arch_small.png

Discussion (0)2
Connectez-vous ou inscrivez-vous pour continuer
Résumé
· Avr 29, 2024
Résumé
· Avr 29, 2024
Article
· Avr 29, 2024 5m de lecture

Tasks flow with InterSystems IRIS Workflow Engine - Introduction

For some time I have been planning to do some type of proof of concept with the Workflow functionality, which, like so many other functionalities present in IRIS, tends to go quite unnoticed by our clients (and for which I say mea culpa). That's why I decided a few days ago to develop an example of how to configure and exploit this functionality by connecting it with a user interface developed in Angular.

To avoid a very long article and make it more accessible, I am going to divide it into 3. In this first article I will present the functionality of Workflow as well as the example that we are going to solve. The second article will go into detail about the configuration and implementation of the production that will be responsible for managing the Workflow. Finally we will show how to access the information available in our Worflow through a web application.

InterSystems IRIS Workflow Engine

What better way to explain what this Workflow functionality is than to copy the description given in the IRIS documentation.

A workflow management system automates the distribution of tasks among users. Automating the distribution of tasks according to a predefined strategy makes task assignment more efficient and task execution more responsible. A typical example is a help desk application that accepts problem reports from customers, sends the reports to members of the appropriate organizations for action, and, once the problem is resolved, reports the results to the customer.

InterSystems IRIS Workflow Engine provides a much higher level of functionality than traditional, stand-alone workflow management systems.

Where do we find the Workflow functionalities in our IRIS? Very simple, from the Management Portal:

Let's briefly explain each of the available options before getting into the example project.

Workflow Roles

This option refers to roles in which we will classify the users who will use the functionality. The definition of role is somewhat confusing, I particularly prefer to see it more as types of tasks that we can create from our production. The name assigned to these roles must match the names of the Business Operations that we will later declare in our production to create tasks associated with said roles.

Workflow Users

IRIS users who can be assigned to different tasks will be associated with one or more roles. Users must be registered with IRIS.

Workflow Tasks

List of tasks created in the system with their associated information. From this window, tasks can be assigned to the different users corresponding to the task role.

What are these tasks? Very simple, the tasks are instances of the EnsLib.Workflow.TaskRequest class, the object of this type will be sent from the Business Process in which it has been generated to a Business Operation of the class EnsLib.Workflow.Operation and with the name of the role that we have previously created. This action will in turn create an instance of the EnsLib.Workflow.TaskResponse class. The Business Operation will not return a response until the CompleteTask method of the TaskResponse class instance is executed.

Workflow Worklist

Similar to the previous functionality, it also shows us a list of tasks with the information associated with them.

Workflow example

The project that you can find associated with this article presents a simplified example of a solution to a typical problem of health organizations such as the treatment of chronic patients. These types of patients require continuous control and strict monitoring for which in many cases the professionals involved in care do not have the most appropriate means.

In the example we are going to see how we can monitor patients with hypertension. We will assume that patients take their blood pressure daily with a blood pressure monitor that will send the reading to the server on which our InterSystems IRIS is installed. In the event that the blood pressure reading exceeds 140 systolic and 90 diastolic values, the patient will be informed that the blood pressure must be taken a second time after a certain time and, if the reading exceeds the limits again, both the patient and the doctor will be informed of the situation so that they can decide what action to take.

To do this, we will divide this task flow into two stages:

Stage 1: Receiving daily blood pressure reading.

  1. Reception in the production of HL7 message with blood pressure measurements.
  2. Checking the existence of the user in the system (and creating it if it does not exist), subsequently registering the user in the roles involved in the workflow.
  3. Extraction of blood pressure data and comparison with the alert criterion.
  4. If the data exceeds the alert criteria:
    1. Creation of a task for the patient informing them of the situation and requesting a new blood pressure measurement.
    2. Creation of automatic task to manage the second blood pressure reading.
  5. If the data does not exceed the alert criteria, the process is closed until the next reading is received the next day.

Stage 2: Reception of second reading after the first reading exceeds the alert values.

  1. Reception of the HL7 message with the second data reading.
  2. Pending automatic task recovery.
  3. If blood pressure levels exceed the alert criteria:
    1. The automatic task is closed indicating the warning status.
    2. A manual task is created for the doctor reporting the patient's situation.
    3. A manual task is created for the patient alerting them to the situation and that their doctor has been informed.
  4. If levels do not exceed alert criteria:
    1. The automatic task is closed indicating that there is no danger.

In the next article we will go into more detail on the design of our flow chart in charge of reflecting what was stated above.

User interface

As you have seen in the attached screenshots, the user interface that InterSystems IRIS provides for task management is, to say the least, quite spartan, but one of the advantages we have with IRIS is that we can create our own API REST to manage our task flow in a very simple way, we will discuss this point in our last article.

To offer a friendly interface to users, we have developed a small web application in Angular using Angular Material that will allow us to create an interface simulating a mobile application.

This mobile application will connect to InterSystems IRIS using JSON Web Tokens and will make HTTP requests to a specific web application published in IRIS, in such a way that the actions taken by the different actors on the tasks are reflected in the defined task flow.

In the next chapter...

After this introduction to the Workflow functionality, in our next article we will show how to implement the task flow necessary to solve the example that we have presented using a BPL, we will configure the entire production and we will see what the main classes involved in the Workflow are like (EnsLib.Workflow.TaskRequest and EnsLib.Workflow.TaskResponse).

Thank you all very much for your attention!

2 Comments
Discussion (2)2
Connectez-vous ou inscrivez-vous pour continuer
Article
· Avr 29, 2024 6m de lecture

Flujos de tareas con InterSystems IRIS Workflow Engine - Introducción

Desde hace un tiempo tenía pendiente hacer algún tipo de prueba de concepto con la funcionalidad de Workflow, la cual, como tantas otras funcionalidades presentes en IRIS, suele pasar bastante desapercibida para nuestros clientes (y por lo cual entono el mea culpa). Por ello me decidí hace unos días a desarrollar un ejemplo de cómo configurar y explotar esta funcionalidad conectándola con una interfaz de usuario desarrollada en Angular.

Para evitar un articulo demasiado largo y hacerlo más asequible voy a dividirlo en 3 entregas. En este primer artículo presentaré la funcionalidad de Workflow así como el ejemplo que vamos a plantear. El segundo artículo entrará en el detalle de la configuración y la implementación de la producción que se encargará de gestionar el Workflow. Finalmente mostraremos como acceder a la información disponible en nuestro Worflow mediante una aplicación web.

InterSystems IRIS Workflow Engine

Qué mejor forma de explicar qué es esta funcionalidad de Workflow que copiar la descripción que da la documentación de IRIS.

Un sistema de gestión de flujo de trabajo automatiza la distribución de tareas entre los usuarios. Automatizar la distribución de tareas de acuerdo con una estrategia predefinida hace que la asignación de tareas sea más eficiente y su ejecución más responsable. Un ejemplo típico es una aplicación de escritorio de ayuda que acepta informes de problemas de los clientes, envía los informes a los miembros de las organizaciones apropiadas para que tomen medidas y, una vez resuelto el problema, informa los resultados al cliente.

InterSystems IRIS Workflow Engine proporciona un nivel mucho más alto de funcionalidad que los sistemas tradicionales e independientes de gestión de flujo de trabajo.

¿Donde encontramos las funcionalidades de Worflow en nuestro IRIS? Muy sencillo, desde el portal de gestión:

Expliquemos someramente cada una de las opciones disponibles antes de meternos con el proyecto de ejemplo.

Workflow Roles

Esta opción hace referencia a roles en los que encuadraremos a los usuarios que harán uso de la funcionalidad. La definición de rol es un tanto confusa, particularmente yo prefiero verlo más como tipos de tareas que podremos crear desde nuestra producción. El nombre asignado a estos roles deberá coincidir con los nombres de las Business Operations que posteriormente declararemos en nuestra producción para crear tareas asociadas a dichos roles.

Workflow Users

Usuarios de IRIS que podrán ser asignados a las diferentes tareas, se asociarán con uno o más roles. Los usuarios deben estar dados de alta en IRIS.

Workflow Tasks

Lista de tareas creadas en el sistema con su información asociada, desde esta ventana se podrán asignar tareas a los diferentes usuarios correspondientes al rol de la tarea.

¿Qué son estas tareas? Muy sencillo, las tareas son instancias de la clase EnsLib.Workflow.TaskRequest, el objeto de este tipo se enviará desde el Business Process en el que se ha generado a una Business Operation de la clase EnsLib.Workflow.Operation y con el nombre del rol que hayamos creado previamente. Esta acción creará a su vez una instancia de la clase EnsLib.Workflow.TaskResponse. El Business Operation no retornará respuesta hasta que no se ejecute el método de CompleteTask de la instancia de la clase TaskResponse.

Workflow Worklist

Similar a la anterior funcionalidad, nos muestra también una la lista de tareas con la información asociada a las mismas pero en este caso únicamente las que están activas.

 Ejemplo de Workflow

El proyecto que podéis encontrar asociado a este artículo plantea un ejemplo simplificado de solución a un problema típico de las organizaciones de salud como es el del tratamiento de pacientes crónicos. Este tipo de pacientes exigen un control continuado y un seguimiento estricto para el que en muchas ocasiones los profesionales involucrados en los cuidados no cuentan con los medios más adecuados.

En el ejemplo vamos a ver cómo se puede realizar un seguimiento de pacientes con hipertensión. Supondremos que los pacientes se toman diariamente la tensión arterial con un tensiómetro que remitirá la lectura al servidor en el que se encuentra instalado nuestro InterSystems IRIS. En el caso de que la lectura de la tensión arterial se superen los valores 140 de sistólica y 90 de diastólica se informará al paciente de que deberá tomarse una segunda vez la tensión pasado un determinado tiempo y, si la lectura vuelve a superar los límites, se informará tanto al paciente como al médico de la situación para que este decida qué medida tomar.

Para ello dividiremos este flujo de tareas en dos etapas:

Etapa 1: Recepción de lectura diaria de tensión arterial.

  1. Recepción en la producción de mensaje HL7 con las medidas de tensión arterial.
  2. Comprobación de la existencia del usuario en el sistema (y creación del mismo si no existe), posteriormente registro del usuario en los roles implicados en el workflow.
  3. Extracción de los datos de tensión arterial y comparación con el criterio de alerta.
  4. Si los datos superan los criterios de alerta:
    1. Creación de tarea para el paciente informándole de la situación y solicitándole una nueva toma de la tensión arterial.
    2. Creación de tarea automática para gestionar la segunda lectura de la tensión arterial.
  5. Si los datos no superan los criterios de alerta se cierra el proceso hasta la siguiente lectura que se reciba el día siguiente.

Etapa 2: Recepción de segunda lectura tras superar la primera lectura los valores de alerta.

  1. Recepción del mensaje de HL7 con la segunda lectura.
  2. Recuperación de la tarea automática pendiente.
  3. Si los niveles de tensión arterial superan los criterios de alerta:
    1. Se cierra la tarea automática indicando el estado de aviso.
    2. Se crea una tarea manual para el médico informando de la situación del paciente.
    3. Se crea una tarea manual para el paciente alertando de la situación y de que se ha informado a su médico.
  4. Si los niveles no superan los criterios de alerta:
    1. Se cierra la tarea automática indicando en la misma que no hay peligro.

En el próximo artículo entraremos más en detalle en el diseño de nuestro diagrama de flujo encargado de reflejar lo expuesto anteriormente.

Interfaz de usuario

Como habéis podido observar en los pantallazos adjuntos la interfaz de usuario que InterSystems IRIS proporciona para la gestión de tareas es, por decirlo de alguna manera, bastante espartana, pero una de las ventajas que tenemos con IRIS es que podemos crear nuestra propia API Rest para gestionar nuestro flujo de tareas de una forma sencillísima, este punto lo trataremos en nuestro último artículo.

Para ofrecer una interfaz amigable a los usuarios hemos desarrollado una pequeña aplicación web en Angular utilizando Angular Material que nos permitirá crear una interfaz simulando una aplicación de móvil. 

Esta aplicación móvil se conectará a InterSystems IRIS haciendo uso de JSON Web Tokens y realizará peticiones HTTP a una determinada aplicación web publicada en IRIS, de tal forma que las acciones que tomen los diferentes actores sobre las tareas se vean reflejadas sobre el flujo de tareas definido.

En el próximo capítulo...

Tras esta introducción  a la funcionalidad de Workflow en nuestro próximo artículo mostraremos como implementar mediante un BPL el flujo de tareas necesario para resolver el ejemplo que hemos presentado, configuraremos la producción al completo y veremos como son las principales clases involucradas en el Workflow (EnsLib.Workflow.TaskRequest y EnsLib.Workflow.TaskResponse).

¡Muchas gracias a todos por vuestra atención!

Discussion (0)1
Connectez-vous ou inscrivez-vous pour continuer