Пример #1
0
def datasetHandler(request, *, dataset, info_role):
    # Test des droits d'édition du dataset si modification
    if dataset.id_dataset is not None:
        user_cruved = cruved_scope_for_user_in_module(
            id_role=info_role.id_role,
            module_code="METADATA",
        )[0]
        dataset_cruved = dataset.get_object_cruved(info_role, user_cruved)
        #verification des droits d'édition pour le dataset
        if not dataset_cruved['U']:
            raise InsufficientRightsError(
                "User {} has no right in dataset {}".format(
                    info_role.id_role, dataset.id_dataset),
                403,
            )
    else:
        dataset.id_digitizer = info_role.id_role
    datasetSchema = DatasetSchema()
    dataset, errors = datasetSchema.load(request.get_json(), instance=dataset)
    if bool(errors):
        log.error(errors)
        raise BadRequest(errors)

    DB.session.add(dataset)
    DB.session.commit()
    return dataset
Пример #2
0
def get_dataset(info_role, id_dataset):
    """
    Get one dataset

    .. :quickref: Metadata;

    :param id_dataset: the id_dataset
    :param type: int
    :returns: dict<TDataset>
    """
    datasetSchema = DatasetSchema()
    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role,
        module_code="METADATA",
    )[0]

    datasetSchema.context = {
        'info_role': info_role,
        'user_cruved': user_cruved
    }

    dataset = DB.session.query(TDatasets).get(id_dataset)
    if not dataset:
        raise NotFound('Dataset "{}" does not exist'.format(id_dataset))

    return datasetSchema.jsonify(dataset)
Пример #3
0
def get_export_pdf_dataset(id_dataset, info_role):
    """
    Get a PDF export of one dataset
    """
    dataset = TDatasets.query.get_or_404(id_dataset)
    if not dataset.has_instance_permission(int(info_role.value_filter)):
        raise Forbidden(
            "Vous n'avez pas les droits d'exporter ces informations")

    dataset_schema = DatasetSchema(only=[
        'nomenclature_data_type',
        'nomenclature_dataset_objectif',
        'nomenclature_collecting_method',
        'acquisition_framework',
    ])
    dataset = dataset_schema.dump(dataset)

    if len(dataset.get("dataset_desc")) > 240:
        dataset["dataset_desc"] = dataset.get("dataset_desc")[:240] + "..."

    dataset["css"] = {
        "logo": "Logo_pdf.png",
        "bandeau": "Bandeau_pdf.png",
        "entite": "sinp",
    }
    dataset["title"] = current_app.config["METADATA"]["DS_PDF_TITLE"]

    date = dt.datetime.now().strftime("%d/%m/%Y")

    dataset["footer"] = {
        "url":
        current_app.config["URL_APPLICATION"] + "/#/metadata/dataset_detail/" +
        id_dataset,
        "date":
        date,
    }

    filename = "jdd_{}_{}_{}.pdf".format(
        id_dataset,
        secure_filename(dataset["dataset_shortname"]),
        dt.datetime.now().strftime("%d%m%Y_%H%M%S"),
    )

    try:
        f = open(str(BACKEND_DIR) + "/static/images/taxa.png")
        f.close()
        dataset["chart"] = True
    except IOError:
        dataset["chart"] = False

    # Appel de la methode pour generer un pdf
    pdf_file = fm.generate_pdf("dataset_template_pdf.html", dataset, filename)
    pdf_file_posix = Path(pdf_file)

    return send_from_directory(str(pdf_file_posix.parent),
                               pdf_file_posix.name,
                               as_attachment=True)
Пример #4
0
def datasetHandler(dataset, data):
    datasetSchema = DatasetSchema(
        only=["cor_dataset_actor", "modules", "cor_territories"],
        unknown=EXCLUDE)
    try:
        dataset = datasetSchema.load(data, instance=dataset)
    except ValidationError as error:
        raise BadRequest(error.messages)

    DB.session.add(dataset)
    DB.session.commit()
    return dataset
Пример #5
0
def create_dataset():
    """
    Post one Dataset data
    .. :quickref: Metadata;
    """
    return DatasetSchema().jsonify(
        datasetHandler(dataset=TDatasets(id_digitizer=g.current_user.id_role),
                       data=request.get_json()))
Пример #6
0
def get_dataset(info_role, id_dataset):
    """
    Get one dataset

    .. :quickref: Metadata;

    :param id_dataset: the id_dataset
    :param type: int
    :returns: dict<TDataset>
    """
    dataset = TDatasets.query.get_or_404(id_dataset)
    if not dataset.has_instance_permission(scope=int(info_role.value_filter)):
        raise Forbidden(
            f"User {g.current_user} cannot read dataset {dataset.id_dataset}")

    dataset_schema = DatasetSchema(only=[
        'creator',
        'cor_dataset_actor',
        'cor_dataset_actor.nomenclature_actor_role',
        'cor_dataset_actor.organism',
        'cor_dataset_actor.role',
        'modules',
        'nomenclature_data_type',
        'nomenclature_dataset_objectif',
        'nomenclature_collecting_method',
        'nomenclature_data_origin',
        'nomenclature_source_status',
        'nomenclature_resource_type',
        'cor_territories',
        'acquisition_framework',
        'acquisition_framework.creator',
        'acquisition_framework.cor_af_actor',
        'acquisition_framework.cor_af_actor.nomenclature_actor_role',
        'acquisition_framework.cor_af_actor.organism',
        'acquisition_framework.cor_af_actor.role',
    ])

    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role,
        module_code="METADATA",
    )[0]
    dataset_schema.context = {'user_cruved': user_cruved}

    return dataset_schema.jsonify(dataset)
Пример #7
0
def create_dataset(info_role):
   """
   Post one Dataset data
   .. :quickref: Metadata;
   """

   # create new dataset
   return DatasetSchema().jsonify(
       datasetHandler(request=request, dataset=TDatasets(), info_role=info_role)
   )
Пример #8
0
def update_dataset(id_dataset, info_role):
    """
    Post one Dataset data for update dataset
    .. :quickref: Metadata;
    """

    dataset = DB.session.query(TDatasets).get(id_dataset)

    if not dataset:
        return {"message": "not found"}, 404

    return DatasetSchema().jsonify(
        datasetHandler(request=request, dataset=dataset, info_role=info_role))
Пример #9
0
def update_dataset(id_dataset, info_role):
    """
    Post one Dataset data for update dataset
    .. :quickref: Metadata;
    """

    dataset = TDatasets.query.filter_by_readable().get_or_404(id_dataset)
    if not dataset.has_instance_permission(scope=int(info_role.value_filter)):
        raise Forbidden(
            f"User {g.current_user} cannot update dataset {dataset.id_dataset}"
        )
    # TODO: specify which fields may be updated
    return DatasetSchema().jsonify(
        datasetHandler(dataset=dataset, data=request.get_json()))
Пример #10
0
def get_export_pdf_dataset(id_dataset, info_role):
    """
    Get a PDF export of one dataset
    """
    datasetSchema = DatasetSchema()

    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role,
        module_code="METADATA",
    )[0]

    datasetSchema.context = {
        'info_role': info_role,
        'user_cruved': user_cruved
    }

    dataset = DB.session.query(TDatasets).get(id_dataset)
    if not dataset:
        raise NotFound('Dataset "{}" does not exist'.format(id_dataset))

    dataset = json.loads((datasetSchema.dumps(dataset)).data)

    #test du droit d'export de l'utilisateur
    if not dataset.get('cruved').get('E'):
        return (
            render_template(
                "error.html",
                error="Vous n'avez pas les droits d'exporter ces informations",
                redirect=current_app.config["URL_APPLICATION"] + "/#/metadata",
            ),
            404,
        )

    if len(dataset.get("dataset_desc")) > 240:
        dataset["dataset_desc"] = dataset.get("dataset_desc")[:240] + "..."

    dataset["css"] = {
        "logo": "Logo_pdf.png",
        "bandeau": "Bandeau_pdf.png",
        "entite": "sinp",
    }
    dataset["title"] = current_app.config["METADATA"]["DS_PDF_TITLE"]

    date = dt.datetime.now().strftime("%d/%m/%Y")

    dataset["footer"] = {
        "url":
        current_app.config["URL_APPLICATION"] + "/#/metadata/dataset_detail/" +
        id_dataset,
        "date":
        date,
    }

    filename = "jdd_{}_{}_{}.pdf".format(
        id_dataset,
        secure_filename(dataset["dataset_shortname"]),
        dt.datetime.now().strftime("%d%m%Y_%H%M%S"),
    )

    try:
        f = open(str(BACKEND_DIR) + "/static/images/taxa.png")
        f.close()
        dataset["chart"] = True
    except IOError:
        dataset["chart"] = False

    # Appel de la methode pour generer un pdf
    pdf_file = fm.generate_pdf("dataset_template_pdf.html", dataset, filename)
    pdf_file_posix = Path(pdf_file)

    return send_from_directory(str(pdf_file_posix.parent),
                               pdf_file_posix.name,
                               as_attachment=True)