New post

Find

Article
· Sep 26, 2024 5m read

IRIS Python nativo - Parte 2

Na sessão anterior, exploramos o processo de instalação e começamos a escrever o IRIS em Python nativo. Agora procederemos a examinar a global percorrida e interatuar com os objetos da classe IRIS

get: esta função se utiliza para obter valores do nó percorrido

def traversal_firstlevel_subscript():
    """
    ^mygbl(235)="test66,62" and ^mygbl(912)="test118,78"
    """
    for  i in irispy.node('^mygbl'):
        print(i, gbl_node.get(i,''))

 

node e items: percorrido de um só nível com node  e obtenção dos valores da mesma maeira que $Order(^mygbl(subscript), direction, data).

#single level traversal
def traversal_dollar_order_single_level():
    for  sub,val in irispy.node('^mygbl').items():
         print('subscript:',sub,' value:', val)
# multi level traversal
def traversal_dollar_order_multi_level():
    for  sub,val in irispy.node('^mygbl').items():
         print(f'sub type is: {type(sub)} {sub} and val type is {type(val)}')
         for sub1,val1 in irispy.node('^mygbl',sub).items():
            print('subscript:',sub1,' value:', val1)
        

 

nextsubscript: diferente do código anterior, pode usar nextsubstricpt para obter o subíndice seguinte facilmente.

def traversal_dollar_order_use_nextsubscript():
      direction = 0
      next_sub = ''
      while next_sub != None:
            next_sub = irispy.nextSubscript(direction,'^mygbl', next_sub)
            print(f'next subscript = {next_sub}' )
            next_sub1=''
            if next_sub == None:return
            while next_sub1 != None:
                next_sub1 = irispy.nextSubscript(direction,'^mygbl',next_sub,next_sub1)
                print(f'1st subscript = {next_sub} next subscript {next_sub1}' )

 

Clases e Objetos

Você pode chamar os classmethods (métodos de classe) desde a definição da classe usando a função específica. Como mencionei anteriormente, os Typecast Methods são cruciais para obter a resposta adequada de IRIS.

Antes de continuar, é importante se dar conta de que, diferente dos tipos de dados de IRIS, qie podemos tratar tudo como string, os tipod de dados de Python, como int, str,bool list se classificam como objetos. Cada um desses tipos possui seus próprios atributos e métodos; por exemplo, o tipo de string do Python inclui funções como .upper() .lower() que não são aplicáveis em outros tipos de dados. Em consequência, o IRIS está equipado com a capacidade de converter os valores de cadeia de IRIS em objetos de tipos de dados compatíveis com Python mediante o uso dos Typecast Methods. Essa funcionalidade se aplica de maneira similar aos métodos de classe, funções definidas pelo usuário e procedimentos. Do contrário, você deve utilizar as funções de conversão de tipos de Python para conseguir o tipo de dados desejado.

 

classMethodValue:Chama o Classmethod desde o Python sem iniciar o objeto, da mesma maneira que (por exemplo):

Do ##Class(Test.MYTest).FirstNameGetStored(1)) e obtem um valor predeterminado de tipo "string" em Python. Há diferentes métoods de conversão de tipo disponíveis para o valor de retorno esperado no lugar de string. Por favor, veja o seguinte:

def get_clsmethod_value():
    print(irispy.classMethodValue('Test.MYTest','FirstNameGetStored',1)) #return string 
    date_horolog = irispy.classMethodInteger('Test.MYTest','GetHorolog') #return +$H value
    print(irispy.classMethodVoid('Test.MYTest','SetTestGlobal','test')) # no return resposne

 

classMethodObject: Função importante para instanciar um novo objeto IRIS ou abrir um objeto existente. Configure as propriedades e invoque métodos de instância, etc.

Nuevo objeto IRIS: Inicie o objeto de classe para Test.MYTest e configure as propriedades.

def cls_object_new():
    """
    initiate new object and store
    """
    iris_proxy_obj = irispy.classMethodObject('Test.MYTest','%New','ashok','kumar')

    birthdate_horolog = irispy.classMethodInteger('Test.MYTest','GetHorolog','12/12/1990')
    horolog = irispy.classMethodInteger('Test.MYTest','GetHorolog')
    iris_proxy_obj.set('BirthDate',birthdate_horolog) #set birthdate property
    iris_proxy_obj.set('RegisteredDate',horolog) #set the RegisteredDate property
    status = iris_proxy_obj.invoke('%Save') #call instance method
    return status

 

Abrir objeto IRIS: No código que se segue, abra o objeto da classee Test.MyTest e obtenha os valores de Birthdate e RegisteredDate do objectid "2", e converta RegisteredDate em uma lista Python.

def cls_object_open():
    iris_proxy_obj = irispy.classMethodObject('Test.MYTest','%OpenId',2)
    birth_date = iris_proxy_obj.get('BirthDate')
    full_name iris_proxy_obj.InvokeString("GetFullName")
    data = [birth_date, iris_proxy_obj.get('RegisteredDate')]
    return data

 

Definição de classe IRIS que utilizei para a demonstração do código de classe e objeto em Python.

 
Spoiler

 

Typecast methods:

Estes são alguns métodos typecast para recuperar valores de retorno adequados de IRIS:

classMethodValue() - para chamar a métodos de classe gerais.

classMethodInteger - Devolve um valor inteiro
classMethodVoid - Sem valor de retorno
classMethodValue - String por padrão
classMethodFloat - Valor de retorno float

invoke() - se utiliza para chamar aos métodos de instância. Você deve iniciar o objeto para chamar a esta invocação de funções

invokeString - String por padrão
invokeFloat - valor de retorno float
invokeInteger - valor de retorno inteiro

 

Cobriremos as funções, chamadas a procedimentos em rotinas e outras funcionalidades no próximo artigo.

Discussion (0)1
Log in or sign up to continue
Question
· Sep 26, 2024

Create a "class variable" and a "singleton".

Hi,

I tried to create what is know as a "class variable".  As far as I understand the only analogy to class variables would be the "class parameters".

I tried to use a class parameter but I cannot change its value at runtime.

Parameter STATUSES = {{}};

Property repr As %String;

Method %OnNew(repr) As %Status
{
    w ##class(Test...).#STATUSES
    w ..#STATUSES

    ...

}

When I get ..#STATUSES, it is a string like "5@%Library.DynamicObject". This is a string, not a pointer to an object.

I tried to define STATUSES as Parameter STATUSES  As CONFIGVALUE = {{}};  and change the value with  

d $system.OBJ.UpdateConfigParam("Test","STATUSES",{"a":10})  but it has no effect. 

I need  a class variable that is updated from %OnNew as a singleton . I try to make a class variable dictionary that keeps the instances defined so far.

My questions are, how to create a singleton and how to define a class variable ?

 

Greetings,

6 Comments
Discussion (6)3
Log in or sign up to continue
Discussion (0)1
Log in or sign up to continue
Announcement
· Sep 26, 2024

Technological Bonuses Results for Developer Tools Contest 2024

Hi Developers!

We are happy to present the bonuses page for the applications submitted to the DevTools Contest 2024!

Project

Vector Search

Embedded Python

WSGI Web Apps

InterSystems Interoperability

IRIS BI

VSCode Plugin

FHIR Tools

Docker

IPM

Online Demo

Community Idea Implementation

Find a bug

Code quality

First Article on DC

Second Article on DC

Video on YouTube

YouTube Short

First Time Contribution

Total Bonus

Nominal 3 3 2 3 3 3 3 2 2 2 4 2 1 2 1 3 1 3 43
Code-Scanner               2 2 2     1 2 1 3     13
DX Jetpack for VS Code           3       2       2   3     10
ks-iris-lib       3       2 2       1         3 11
iris-ccd-devtools               2           2   3   3 10
db-management-tool               2   2       2 1 3 1   11
sql-embeddings 3 3           2 2 2     1 2   3     18
pxw-lib-sql               2         1         3 6
Irisheimer                           2     1   3
IRIS-Test-Data-Generator   3           2 2         2       3 12
iris-DataViz   3           2 2       1 2   3     13
IPM in VS Code           3       2 4     2 1 3     15
IRIS-Log-Monitor               2 2                 3 7
IOP REST Client Framework   3   3       2 2   4         3   3 20
iris-api-interface-generator   3 2 3       2                     10
iterm   3 2         2 2         2         11
iris-dev-codeinspector               2 2         2       3 9
IRIS-API-Template       3       2 2         2       3 12

Please apply with your comments for new implementations and corrections to be made here in the comments or in Discord.

15 Comments
Discussion (15)3
Log in or sign up to continue
Question
· Sep 26, 2024

HTTP request with Cookies

Hi Guys,

I've created a webservice where a third party web application that can communicate with Ensemble via webservices to post and get data in from of JSON, first call is a post call to login with user/password and Ensemble responds with success or failure than the following get calls, but I've been advised that I also need to return a Cookie to control the exchange and the session for a specific user, I'm not familiar with Cookie so any suggestions, how can I create a an authentication cookie and do i need to add it to my next Get calls ?       

 

Thanks

Discussion (0)1
Log in or sign up to continue