module1.py 6.03 KB
#!/usr/bin/env python3


'''
=================================================================
    PACKAGES IMPORT
=================================================================
'''

# --- GENERAL PURPOSE IMPORT ---

import pykwalify.core
import sys
import yaml, logging, os, pickle, time
from datetime import datetime
from pykwalify.errors import PyKwalifyException,SchemaError
from pathlib import Path

# --- PROJECT SPECIFIC IMPORT ---

from django.conf import settings as djangosettings
from common.models import AgentSurvey, AgentCmd, AgentLogs
from src.core.pyros_django.obsconfig.configpyros import ConfigPyros
from device_controller.abstract_component.device_controller import (
    DCCNotFoundException, UnknownGenericCmdException, UnimplementedGenericCmdException, UnknownNativeCmdException
)



'''
=================================================================
    GENERAL MODULE CONSTANTS & FUNCTIONS DEFINITIONS
=================================================================
'''

# - General constants

DEBUG = False

IS_WINDOWS = platform.system() == "Windows"


# - General Functions

def general_function1(arg_a: int=1, arg_b: str='toto', arg_c: float, arg_d: bool) -> float:
    '''
    This function is used for ... blabla ...
    
    Args:
        arg_a: the path of the file to wrap
        arg_b: instance to wrap
        arg_c: toto
        arg_d: whether or not to delete the file when the File instance is destructed

    Returns:
        A buffered writable file descriptor
    
    Raises:
        AttributeError: The ``Raises`` section is a list of all exceptions
            that are relevant to the interface.
        ValueError: If `arg_a` is equal to `arg_b`.
    '''
    
    # comment on a
    a = 1
    
    # comment on b
    b = 2

    return 3.5


def general_function2(a: int, b:int):
    '''
        Commentaires
    '''
    a = 1
    b = 2
    
    return 3



'''
=================================================================
    CLASS MyFirstClass
=================================================================
'''

class MyFirstClass:
    ''' 
    General Comment on the class 
    bla
    bla
    '''

    # The class attributes
    
    # comment on my_attr1
    my_attr1 = {}
    current_file = None
    pickle_file = "obsconfig.p"
    obs_config = None
    devices = None
    computers = None
    agents = None 
    obs_config_file_content = None
    errors = None


    # The class methods

    def __init__(self, a: int, b: float) -> int:
        '''
        Commentaire sur my_method1"

        Args:
            a: blabla

        Returns:
            bool: [description]
        '''

        c = 1
        d = 2
        
        return False


    def my_method2(self, a: int, b: float):
        a = 1
        b = 2


#TODO: *args et **all_kwargs

    def check_and_return_config(self, yaml_file: str, schema_file: str) -> dict:
        '''
        Check if yaml_file is valid for the schema_file and return an dictionary of the config file

        Args:
            yaml_file: Path to the config_file to be validated
            schema_file: Path to the schema file 

        Returns:
            dict: dictionary of the config file (with values)
        '''
        # disable pykwalify error to clean the output
        #####logging.disable(logging.ERROR)
        try:
            can_yaml_file_be_read = False
            while can_yaml_file_be_read != True:
                if os.access(yaml_file, os.R_OK):
                    can_yaml_file_be_read = True
                else:
                    print(f"{yaml_file} can't be accessed, waiting for availability")
                    time.sleep(0.5)

            c = pykwalify.core.Core(source_file=yaml_file, schema_files=[self.SCHEMA_PATH+schema_file])
            return c.validate(raise_exception=True)
        except SchemaError:
            for error in c.errors:
                print("Error :",str(error).split(". Path")[0])
                print("Path to error :",error.path)
                self.errors = c.errors
            return None
        except IOError:
            print("Error when reading the observatory config file")


    #TODO: @classmethod (avec cls)
    @staticmethod
    def check_config(yaml_file: str, schema_file: str) -> any:
        """
        Check if yaml_file is valid for the schema_file and return a boolean or list of errors according the schema

        Args:
            yaml_file (str): Path to the config_file to be validated
            schema_file (str): Path to the schema file 

        Returns:
            any: boolean (True) if the configuration is valid according the schema or a list of error otherwise
        """
        # disable pykwalify error to clean the output
        ####logging.disable(logging.ERROR)
        try:
            can_yaml_file_be_read = False
            while can_yaml_file_be_read != True:
                if os.access(yaml_file, os.R_OK):
                    can_yaml_file_be_read = True
                else:
                    print(f"{yaml_file} can't be accessed, waiting for availability")
                    time.sleep(0.5)
        
            c = pykwalify.core.Core(source_file=yaml_file, schema_files=[schema_file])
            c.validate(raise_exception=True)
            return True
        except SchemaError:
            for error in c.errors:
                print("Error :",str(error).split(". Path")[0])
                print("Path to error :",error.path)
                
            return c.errors
        except IOError:
            print("Error when reading the observatory config file")



class MySecondClass:
    ''' General Comment on the class '''
    pass


#TODO: Exceptions custom
#TODO: générer doc exemple avec Sphinx



'''
=================================================================
    Main function
=================================================================
'''
def main():
    a = 1
    b = 2
    c = 3



'''
=================================================================
    Exec of main function
=================================================================
'''
if __name__ == "__main__": 

    main()