Ejemplo n.º 1
0
    def validate_form(self, form):
        """
            validation personnalisée du form
        """
        # Essai de récupérer en BD la vue sql déclarée
        # Delete n'a pas d'attribut view_name
        view_name = getattr(form, 'view_name', '')
        schema_name = getattr(form, 'schema_name', '')
        geometry_field = getattr(form, 'geometry_field', None)
        geometry_srid = getattr(form, 'geometry_srid', None)
        if (is_form_submitted() and view_name and schema_name):
            try:
                query = GenericQuery(DB.session,
                                     view_name.data,
                                     schema_name.data,
                                     geometry_field=geometry_field.data,
                                     filters=[])
                query.return_query()

                if geometry_field.data and geometry_srid.data is None:
                    raise KeyError(
                        "field Geometry srid is mandatory with Geometry field")

            except Exception as exp:
                flash(exp, category='error')
                return False

        return super(ExportView, self).validate_form(form)
Ejemplo n.º 2
0
def etalab_export():
    """
        TODO : METHODE NON FONCTIONNELLE A EVALUEE
    """
    if not blueprint.config.get('etalab_export'):
        return to_json_resp(
            {
                'api_error': 'etalab_disabled',
                'message': 'Etalab export is disabled'
            },
            status=501)

    from datetime import time
    from geonature.utils.env import DB
    from .rdf import OccurrenceStore

    conf = current_app.config.get('EXPORTS')
    export_etalab = conf.get('etalab_export')
    seeded = False
    if os.path.isfile(export_etalab):
        seeded = True
        midnight = datetime.combine(datetime.today(), time.min)
        mtime = datetime.fromtimestamp(os.path.getmtime(export_etalab))
        ts_delta = mtime - midnight

    if not seeded or ts_delta.total_seconds() < 0:
        store = OccurrenceStore()
        query = GenericQuery(DB.session,
                             'export_occtax_sinp',
                             'pr_occtax',
                             geometry_field=None,
                             filters=[])
        data = query.return_query()
        for record in data.get('items'):
            event = store.build_event(record)
            obs = store.build_human_observation(event, record)
            store.build_location(obs, record)
            occurrence = store.build_occurrence(event, record)
            organism = store.build_organism(occurrence, record)
            identification = store.build_identification(organism, record)
            store.build_taxon(identification, record)
        try:
            with open(export_etalab, 'w+b') as xp:
                store.save(store_uri=xp)
        except FileNotFoundError:
            response = Response(
                response="FileNotFoundError : {}".format(export_etalab),
                status=500,
                mimetype='application/json')
            return response

    return send_from_directory(os.path.dirname(export_etalab),
                               os.path.basename(export_etalab))
Ejemplo n.º 3
0
    def _get_data(self,
                  export_,
                  geom_column_header=None,
                  filters=None,
                  limit=10000,
                  offset=0):
        """
            Fonction qui retourne les données de l'export passé en paramètre
            en applicant des filtres s'il y a lieu

            .. :quickref: lance une requete qui récupère les données pour un export donné


            :query Export export_: Définition de l'export
            :query str geom_column_header: Nom de la colonne géometry si elle existe
            :query {} filters: Filtres à appliquer sur les données
            :query int limit: Nombre maximum de données à retourner
            :query int offset: Numéro de page à retourner

            **Returns:**

            .. sourcecode:: http

                {
                    'total': Number total of results,
                    'total_filtered': Number of results after filteer ,
                    'page': Page number,
                    'limit': Limit,
                    'items': data on GeoJson format
                    'licence': information of licence associated to data
                }

        """

        if not filters:
            filters = dict()

        query = GenericQuery(self.session, export_.view_name,
                             export_.schema_name, geom_column_header, filters,
                             limit, offset)
        data = query.return_query()

        # Ajout licence
        if export_:
            export_license = (export_.as_dict(True)).get('licence', None)
            data['license'] = dict()
            data['license']['name'] = export_license.get('name_licence', None)
            data['license']['href'] = export_license.get('url_licence', None)

        return (query.view.db_cols, data)