def get_default_decoders(): return [ codecs.CoreJSONCodec(), codecs.JSONCodec(), codecs.TextCodec(), codecs.DownloadCodec(), ]
def __init__(self, host, port, user, token, params_callback=None, message_callback=None): self.base_url = self.get_service_url(host, port) self.client = Client( decoders=[ codecs.CoreJSONCodec(), # application/vnd.coreapi+json codecs.JSONCodec() # application/json ], transports=[ transports.CommandHTTPSTransport( auth=auth.CommandClientTokenAuthentication(user=user, token=token, scheme='Token', domain='*'), params_callback=params_callback, message_callback=message_callback) # https only ]) self.schema = self.client.get(self.base_url)
class Client(itypes.Object): DEFAULT_TRANSPORTS = [transports.HTTPTransport()] DEFAULT_DECODERS = [ codecs.CoreJSONCodec(), codecs.JSONCodec(), codecs.TextCodec() ] def __init__(self, decoders=None, transports=None): if decoders is None: decoders = self.DEFAULT_DECODERS if transports is None: transports = self.DEFAULT_TRANSPORTS self._decoders = itypes.List(decoders) self._transports = itypes.List(transports) @property def decoders(self): return self._decoders @property def transports(self): return self._transports def get(self, url, force_codec=False): link = Link(url, action='get') # Perform the action, and return a new document. transport = determine_transport(self.transports, link.url) return transport.transition(link, self.decoders, force_codec=force_codec) def reload(self, document, force_codec=False): url = document.url link = Link(url, action='get') # Perform the action, and return a new document. transport = determine_transport(self.transports, link.url) return transport.transition(link, self.decoders, force_codec=force_codec) def action(self, document, keys, params=None, action=None, encoding=None, transform=None): if isinstance(keys, string_types): keys = [keys] # Validate the keys and link parameters. link, link_ancestors = _lookup_link(document, keys) if (action is not None) or (encoding is not None) or (transform is not None): # Handle any explicit overrides. action = link.action if (action is None) else action encoding = link.encoding if (encoding is None) else encoding transform = link.transform if (transform is None) else transform link = Link(link.url, action=action, encoding=encoding, transform=transform, fields=link.fields) # Perform the action, and return a new document. transport = determine_transport(self.transports, link.url) return transport.transition(link, self.decoders, params=params, link_ancestors=link_ancestors)
class VillesSimilaires(object): """ Cette classe est appelée lors de l'autocomplementation d'une ville recherchée """ # on definit l'API (url de base) __api_de_base = 'https://geo.api.gouv.fr/' # limit du nombre de ville à afficher dens l'autocomplementation __limite = 10 decoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()] def __init__(self, saisi): # on enleve toutes les espaces autour de la valeur saisie self.__saisi = str(saisi).strip() def get_ville_similaire(self): if self.__saisi != '': try: client = Client() # self.__class__.decoders # connexion à l'API document = client.get(self.__class__.__api_de_base + 'communes?nom={nom}' '&fields=population,centre,departement' '&boost=population'.format( nom=self.__saisi)) # cette fonction est un générateur qui nous permet de limiter la recherche def limit_rech(limit=self.__class__.__limite): num = 0 for un in document: yield un num += 1 if num >= limit: break # création d'une liste des villes récupérées les_villes_bruites = [x for x in limit_rech()] # Création d'une nouvelle listes avec mes propes clée:id , value , population etc... # En gros je reformatte les villes envoyées par l'API mes_villes = [] for myid, value in enumerate(les_villes_bruites): mes_villes.append({ 'id': myid, 'value': value['nom'], 'population': value['population'], 'latitude': value['centre']['coordinates'][1], 'longitude': value['centre']['coordinates'][0] }) # cet objet a été crée lors du chargement de ce fichier # enregistrement du dictionnaire des villes je_garde.set_last_list(mes_villes) return json.dumps(mes_villes) except Exception as E: return '' else: return ''
class BaseClient: decoders = [HALCodec(), codecs.JSONCodec()] def __init__(self, uri, elem_class): """ Init from base uri and expected element helper class :param uri: relative uri to base OLS url :param elem_class: helper class expected """ self.client = Client(decoders=self.decoders) self.uri = uri self.elem_class = elem_class def _parse_response(self, received, path=''): logger.debug("Parse response from %s/%s (%s)", self.uri, path, type(received)) if isinstance(received, coreapi.document.Document): return received elif isinstance(received, collections.OrderedDict): return HALParseDocument(received) logger.error('%s/%s did not retrieved a parse-able object object: %s', self.uri, path, type(received)) raise exceptions.UnparsedDocumentException( 'Document (%s) %s could not be parsed' % (received.__class__.__name__, received)) @staticmethod def filters_response(filters): """ Filters queries for search""" logger.debug('Applying filters %s', filters) assert set(filters.keys()).issubset( {'exact', 'fieldList', 'groupField', 'obsoletes', 'ontology', 'queryFields', 'slim', 'type', 'local'}), \ "Unauthorized filter key" if 'fieldList' in filters: if type(filters['fieldList']) is str: assertion_set = set(filters['fieldList'].split(',')) elif type(filters['fieldList'] is set): assertion_set = filters['fieldList'] else: raise AssertionError("Wrong filter FieldList %s" % filters['fieldList']) assert assertion_set.issubset({ 'description', 'id', 'iri', 'is_defining_ontology', 'label', 'obo_id', 'ontology_name', 'ontology_prefix', 'short_form', 'type' }), "Wrong fieldList - check OLS doc" if 'queryFields' in filters: if type(filters['queryFields']) is str: assertion_set = set(filters['queryFields'].split(',')) elif type(filters['queryFields'] is set): assertion_set = filters['queryFields'] else: raise AssertionError("Wrong filter queryFields %s" % filters['queryFields']) assert assertion_set.issubset({ 'annotations', 'description', 'iri', 'label', 'logical_description', 'obo_id', 'short_form', 'synonym' }), "Wrong queryFields - check OLS doc" if 'type' in filters: if type(filters['type']) is str: assertion_set = set(filters['type'].split(',')) elif type(filters['type'] is set): assertion_set = filters['type'] else: raise AssertionError("Wrong filter type %s" % filters['type']) assert assertion_set.issubset({'class', 'property', 'individual', 'ontology', 'term'}), \ "Wrong type - check OLS doc" filters['type'] = filters['type'].replace('term', 'class') if 'exact' in filters: assert filters['exact'] in ['true', 'false' ], '"exact" only accept true|false' if 'groupFields' in filters: assert filters['groupFields'] in [ 'true', 'false' ], '"groupFields" only accept true|false' if 'obsoletes' in filters: assert filters['obsoletes'] in [ 'true', 'false' ], '"obsoletes" only accept true|false' if 'local' in filters: assert filters['local'] in ['true', 'false' ], '"local" only accept true|false' return filters @staticmethod def filters_terms(filters): """ Check filters for terms queries""" logger.debug('Applying filters %s', filters) assert set(filters.keys()).issubset( {'size', 'iri', 'obo_id', 'short_form'}), "Unauthorized filter key" assert len( filters.keys()) <= 1, "Only one filter can be applied at a time" return filters @staticmethod def make_uri(identifier): """ Get identifier format for ontologies """ return urllib.parse.quote_plus(urllib.parse.quote_plus( str(identifier))) def elem_class_instance(self, **data): """ Get an item object from dedicated class expected object :param data: :return: """ return self.elem_class(**data)