0
\$\begingroup\$

I have created the below script in which I'm trying to set up a class for handling a config file, but also defining some functions that I call from the class methods. Not sure if I'm following the best practices when creating a class.

# Python3 program to show that we can create
# instance variables inside methods
import pandas as pd
from datetime import datetime as dt, timedelta as td
import jtp_aux as aux


def import_config_df():
    """
    Imports config dataframe with the values enabled being equal to 'YES'
    Returns:
        dataframe
    """
    df_ = pd.read_excel(
        r'\\path\file.xlsx'
    )
    cond_ = conditions_df(df_, 'ENABLED', 'YES').fillna(False)
    return df_[cond_]


def conditions_df(df_, col_check_, col_value_, match_type_='MATCH'):
    """
    Args:
        df_ (): config dataframe
        col_check_ (): column to check
        col_value_ (): value to check
        match_type_ (): match type being 'MATCH' for full match or 'CONTAINS' for partial match

    Returns:
        Dataframe with the True/False for the rows based on conditions met or not.
    """
    if match_type_ == 'MATCH':
        return df_[col_check_].str.match(col_value_).fillna(False)
    elif match_type_ == 'CONTAINS':
        return df_[col_check_].str.contains(col_value_).fillna(False)
    else:
        return None


def return_config(df_, process_, procedure_, sub_procedure_, type_return_):
    """
    Based on the three first column of the config dataframe, it returns the value enabled
    for it.
    Args:
        df_ (dataframe): 
        process_ (string): first config parameter from config file
        procedure_ (string): second config parameter from config file
        sub_procedure_ (string): third config parameter from config file
        type_return_ (string): 'LIST' (2+ value enabled to concatenate) or 'STRING' (1 value enabled).

    Returns:
        String or list resulting from the configuration inputted.
    """
    cond1 = conditions_df(df_, 'PROCESS', process_)
    cond2 = conditions_df(df_, 'PROCEDURE', procedure_)
    cond3 = conditions_df(df_, 'SUB_PROCEDURE', sub_procedure_)

    if type_return_ == 'LIST':
        return df_[cond1 & cond2 & cond3]['VALUE_ENABLED'].to_list()
    elif type_return_ == 'STRING':
        return df_[cond1 & cond2 & cond3]['VALUE_ENABLED'].astype('str').to_string(index=False)
    else:
        return None


def config_reports(df_, process_, report_day_, auto_manual_):
    """

    Args:
        df_ (): config dataframe
        process_ (): 'REPORTS', 'VALIDATIONS'...
        report_day_ (): for the auto-schedule.
        auto_manual_ (): auto or manual schedule

    Returns: dictionary

    """
    dict_return = {}

    cond1 = conditions_df(df_, 'PROCESS', process_)

    # If auto-scheduled or manually scheduled.
    if auto_manual_ == 'AUTO':
        cond2a = conditions_df(df_, 'SUB_PROCEDURE', 'AUTO_SCHEDULE')
        cond2b = conditions_df(df_, 'VALUE_ENABLED', report_day_, 'CONTAINS')
    else:
        cond2a = conditions_df(df_, 'SUB_PROCEDURE', 'MANUAL_SCHEDULE')
        cond2b = conditions_df(df_, 'VALUE_ENABLED', 'YES')
    # And/or logic
    cond2 = cond2a & cond2b

    procedures_ = df_[cond1 & cond2]['PROCEDURE'].unique()

    for procedure_ in procedures_:
        # Base df for operations
        cond3 = conditions_df(df_, 'PROCEDURE', procedure_)
        df_aux = df_[cond1 & cond3]

        # Fetch config for the PLSQL Code to execute
        cond4 = conditions_df(df_, 'SUB_PROCEDURE', 'PLSQL')
        plsql_ = df_aux[cond4]['VALUE_ENABLED'].astype('str').to_string(index=False)
        plsql_ = '\n'.join(['BEGIN', plsql_, 'END;'])

        # Fetch config for the Cathnas01 path
        cond5 = conditions_df(df_, 'SUB_PROCEDURE', 'PATH_CATHNAS01')
        path_ = df_aux[cond5]['VALUE_ENABLED'].astype('str').to_string(index=False)

        # Fetch config for the name of the file
        cond6 = conditions_df(df_, 'SUB_PROCEDURE', 'FILENAME')
        filename_ = df_aux[cond6]['VALUE_ENABLED'].astype('str').to_string(index=False)

        # Fetch config for the data in the tabs
        cond7 = conditions_df(df_, 'SUB_PROCEDURE', 'EXCEL_CONTENT')
        tabs_data_ = df_aux[cond7][['FIELD2', 'VALUE_ENABLED']].set_index('FIELD2')['VALUE_ENABLED'].to_dict()

        dict_return[procedure_] = (plsql_, path_, filename_, tabs_data_)

    return dict_return


class MyConfigFile:
    def __init__(self, process_):
        self.df = import_config_df()
        self.process = process_

        # Manual or auto-schedule
        self.auto_manual = return_config(self.df, self.process, 'GLOBAL', 'AUTO_MANUAL', 'STRING')

    def getdictreports(self, delta_):
        # Dictionary to iterate for reports
        return config_reports(
            self.df,
            self.process,
            (dt.today() + td(days=delta_)).strftime('%a').upper(),
            self.auto_manual
        )

    def send_errors_mail(self, body_):
        """
        Sends an error mail.
        Args:
            body_ (): mail body

        Returns:
            None
        """
        aux.send_email(
            strfrom=return_config(self.df, self.process, 'ERRORS', 'FROM', 'STRING'),
            vpara=return_config(self.df, self.process, 'ERRORS', 'TO', 'LIST'),
            vcc=return_config(self.df, self.process, 'ERRORS', 'CC', 'LIST'),
            vasunto=return_config(self.df, self.process, 'ERRORS', 'SUBJECT', 'STRING'),
            test_body=body_,
            attachments=r'',
            vprioridad=return_config(self.df, self.process, 'ERRORS', 'PRIORITY', 'STRING'),
            image=None
        )

    def send_confirmation_mail(self, body_):
        """
        Send a confirmation mail if everything successful.
        Args:
            body_ ():

        Returns:

        """
        aux.send_email(
            strfrom=return_config(self.df, self.process, 'CONFIRMATION', 'FROM', 'STRING'),
            vpara=return_config(self.df, self.process, 'CONFIRMATION', 'TO', 'LIST'),
            vcc=return_config(self.df, self.process, 'CONFIRMATION', 'CC', 'LIST'),
            vasunto=return_config(self.df, self.process, 'CONFIRMATION', 'SUBJECT', 'STRING'),
            test_body=body_,
            attachments=r'',
            vprioridad=return_config(self.df, self.process, 'CONFIRMATION', 'PRIORITY', 'STRING'),
            image=None
        )
\$\endgroup\$
3
  • \$\begingroup\$ Hey! Is this a copy paste error: r'\\path\file.xlsx' ? \$\endgroup\$
    – kubatucka
    Nov 8 at 10:39
  • \$\begingroup\$ @kubatucka no, I had there my actual path, but I anonymized it. \$\endgroup\$
    – banana_99
    Nov 8 at 10:57
  • \$\begingroup\$ Please include an example or specification of the config file format. \$\endgroup\$ Nov 8 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.