Reading and writing data to database tables

I would like to share data between actions using database tables. Is that possible? Thanks.

1 Like

Can you expand on what you are specifically trying to do? I’m not completely sure I understand the question or purpose.

Hi Kyle,

There’re many parameters and temporary data that I would like to store in some database tables, and I would like to have control of those tables (add/remove columns, etc). The stored data will be used later either for recovery or executing different logic when the same function runs again.

Thanks for your help.

Great work!!! I really enjoy using Mycodo.

Tuan

You can store and retrieve basic values for Inputs, Outputs, and Functions. See:

I think that would work. Thanks.

Tuan

1 Like

Hi Kyle,

I need to pass data between two different Conditional functions, say C1 and C2. I tried the approach below and it did not work.

In C1, I save some data for C2 using:

self.set_custom_option(“C1”, “Data from C1”)

In C2, I retrieve the data sent by C1 using:

data_from_C1 = self.get_custom_option(“C1”)

This approach does not not work. data_from_C1 is always None.

It seems that the self.set_custom_option(key, data) and self.get_custom_option(key) functions only work within the same Conditional function. Is that correct? If so, can you suggest a way for me to pass data between different Condition functions. For now, C1 passes data to C2 using a flat file.

Thanks,

Tuan

1 Like

Yes, they have their own scope. There is not a global database that all functions store/retrieve data from. Each has their own settings.

You can obtain the settings JSON string (and convert it to a dictionary) from any controller using the following method:

import json
from mycodo.config import MYCODO_DB_PATH
from mycodo.databases.utils import session_scope
from mycodo.databases.models import Conditional

conditional_id = "QWER-ASDF-1234-5678"

with session_scope(MYCODO_DB_PATH) as new_session:
    cond = new_session.query(Conditional).filter(
        Conditional.unique_id == conditional_id).first()
    try:
        custom_options = json.loads(cond.custom_options)
    except:
        custom_options = {}

    if "C1" in custom_options:
        self.logger.info(f"C1 found: {custom_options['C1']}")
    else:
        self.logger.info("C1 not found")

That should work. Thank you so much for taking the time to reply.

Tuan

1 Like