""" Module controlling the available protocols. It is used to parse the parameters of protocols. TODO: Deep explanation """ from tools import const from .fiware import FIWARE from .postgresql import PostgreSQL from .http import Http from .https import Https from .ftp import FTP from .local_prev import LOCAL from .wms import WMS from .tms import TMS from .ags import AGS try: from .local import LOCAL as LOCAL_files except: print('No se pudo importar el local que quieres') # from .google_drive import GoogleDrive from .dropbox import Dropbox from .gjson_virtual import GJsonVirtual class Protocol: """ Class that control some protocol features, mainly it is the responsible of filtervthe allowed protocols and parse its parameters. Attributes ---------- PROTOCOLS: dict Dictionary with the allowed protocols. It contains the protocol name as key andvits implementation (class) as value. Raises ------ ProtocolNotSupportedError: Protocol not found when get the driver from __getitem__ method. ProtocolNotFoundError: Protocol not found when parsing parameters. """ PROTOCOLS = {const.POSTGRESQL_KEY: PostgreSQL, const.HTTP_KEY: Http, const.HTTPS_KEY: Https, const.FIWARE_KEY: FIWARE, const.FTP_KEY: FTP, const.LOCAL_KEY: LOCAL, const.LOCAL_FILES_KEY: LOCAL_files, const.WMS_KEY: WMS, const.TMS_KEY: TMS, const.AGS_KEY: AGS, # const.GOOGLEDRIVE_KEY: GoogleDrive, const.DROPBOX_KEY: Dropbox, const.GJSON_VIRTUAL_PROTOC: GJsonVirtual} protocol_not_supported = type('ProtocolNotSupportedError', (Exception, ), {}) protocol_not_found = type('ProtocolNotFoundError', (Exception, ), {}) @classmethod def _find_on_dict(cls, key, dict_where_seek): """ Method to find a key equals to `key` in `dict_where_seek`. A generator is returned with all occurrences. Parameters ---------- key: str Key to find. dict_where_seek: dict Dictionary to seek. Could have any dictionary children deep. Returns ------- iter: Iterator with all occurrences of the key `key`. """ if hasattr(dict_where_seek, 'items'): childrens_dicts = [] for k, v in dict_where_seek.items(): if k == key: yield v if isinstance(v, dict): childrens_dicts.append(v) for children in childrens_dicts: for result in cls._find_on_dict(key, children): yield result @classmethod def get_from_dict(cls, target_dict): """ Get protocol identification from dictionary. Actually the protocol is identified by the key 'type'. Parameters ---------- target_dict: dict Target dictionary. Returns ------- MasterProtocol: Protocol implementation (python class) identified by the found value. """ protocol = False for possible_driver in list(cls._find_on_dict('type', target_dict)): try: protocol = cls.PROTOCOLS[possible_driver] except KeyError: continue if not protocol: raise cls.protocol_not_found('Protocol did not found in the ' 'specifications') return protocol def __getitem__(self, item): if item not in self.PROTOCOLS: raise self.protocol_not_supported('{} not supported'.format(item)) return self.PROTOCOLS[item]