'Writing to db from python durables engine

I have been trying to write business rules using durables engine in python. The source code is as below :

import pymysql
import pandas as pd
import datetime
from durable.lang import *
from tickets import *

con = pymysql.connect(host='localhost', user='XXXX', password='XXXX', database='nms')

#df_30min = pd.read_sql('select * from recentalarms where dbinserttime > now() - interval 30 minute', con)
df = pd.read_sql('select * from recentalarms', con)
df_tt = pd.read_sql('select tt_id from ticket', con)


format = "%Y%m%d%H%M%S"
time_before_5min = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(minutes=5), format)
time_before_15min = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(minutes=15), format)

with ruleset('nms'):
    @when_all((m.status == 'open') & ( m.instance >= 3) & (m.tt_id == None) & (m.readflag == None ))
    def rule_action1(c):
        tt_id = Ticket.create(domain_prefix,entity=entity,start_time=down_since,severity=severity)
        cursor = con.cursor()
        sql_query = f"UPDATE recentalarm SET read_flag = 'true' , tt_id = '{tt_id}' WHERE id = '{alarm_id}';"
        cursor.execute(sql_query)
        con.commit()
        print(f"1. Create ticket Run Completed")

    @when_all((m.status == 'close') & ( m.uptime <= time_before_15min) & (m.uptime != None))
    def rule_action2(c):
        Ticket.resolve(tt_id,time_stmp)
        cursor = con.cursor()
        sql_query = f"UPDATE recentalarm SET read_flag = 'true' , tt_id = '{tt_id}' WHERE id = '{alarm_id}';"
        cursor.execute(sql_query)
        con.commit()
        print(f"2. Resolve ticket Run Completed")
############some more rules
for i, row in df.iterrows():
    stat = row.status.lower()
    olt = row.oltname
    result = df.iloc[0:i+1]['oltname'] == f'{row.oltname}'
    instance_count = int(result.value_counts()[True])
    ONTPort = row.ONTParentPort
    alarm_id = row.id
    entity = row.entity
    severity = row.severity
    up_since = str(row.eventclosetime)
    down_since = str(row.eventime)
    try:
       post('gponnms', { 'status' : stat , 'instance' : instance_count , 'readflag' : row.read_flag , 'uptime' : up_since , 'downtime' : down_since})
    except:
        pass

con.close()

I have 2 queries.

  1. In the rule_action I require to update the field back in the sql table for read_flag. This is being done through sql query. Is there another way to update the database other than writing sql query in the action function

  2. My second question is in the last there is post message. I need to understand if this is really required.But if I delete this I get error message. The documentation on durables does not give much insight on it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source