Example #1
0
class DemoObjSchema(base_schema.ObjTypeSchema):
    filename = FilenameSchema(
        save=True,
        update=True,
        isdatafile=True,
        test_equal=False,
    )

    foo_float = colander.SchemaNode(colander.Float(), save=True, update=True)

    foo_float_array = colander.SequenceSchema(colander.SchemaNode(
        colander.Float()),
                                              read_only=True)

    timeseries = colander.SequenceSchema(colander.TupleSchema(children=[
        colander.SchemaNode(colander.DateTime(default_tzinfo=None)),
        colander.SchemaNode(colander.Float())
    ]),
                                         read_only=True)

    variable = base_schema.GeneralGnomeObjectSchema(
        acceptable_schemas=[TimeseriesDataSchema, TimeseriesVectorSchema],
        save=True,
        update=True,
        save_reference=True,
    )

    variables = colander.SequenceSchema(base_schema.GeneralGnomeObjectSchema(
        acceptable_schemas=[TimeseriesDataSchema, TimeseriesVectorSchema]),
                                        save=True,
                                        update=True,
                                        save_reference=True)
Example #2
0
def metadata_schema_node(prop: InstrumentedAttribute,
                         model: DeclarativeMeta) -> colander.SequenceSchema:
    """Get the schema of a collection of metadata."""

    # Deferred which returns a dictionary with metadata name as key and metadata definition as value.
    # Needed to get the metadata types on UI side.
    metadata_definitions_dict = colander.deferred(
        lambda node, kw: {
            m["name"]: _translate_available_metadata(m, kw["request"])
            for m in metadata_definitions(kw["request"].registry.settings,
                                          model)
        })

    return colander.SequenceSchema(
        MetadataSchemaNode(
            Metadata,
            name="metadata",
            metadata_definitions=metadata_definitions_dict,
            validator=regex_validator,
            widget=MappingWidget(template="metadata"),
            overrides={"name": {
                "widget": metadata_name_widget(model)
            }},
        ),
        name=prop.key,
        title=prop.info["colanderalchemy"]["title"],
        description=prop.info["colanderalchemy"]["description"],
        metadata_definitions=metadata_definitions_dict,
        widget=SequenceWidget(template="metadatas", category="structural"),
    )
Example #3
0
def children_schema_node(only_groups: bool = False) -> colander.SequenceSchema:
    """Geth the sequence to the children nodes."""
    return colander.SequenceSchema(
        ChildSchemaNode(
            LayergroupTreeitem,
            name="layergroup_treeitem",
            widget=ChildWidget(
                input_name="treeitem_id",
                model=TreeItem,
                label_field="name",
                icon_class=lambda treeitem: f"icon-{treeitem.item_type}",
                edit_url=treeitem_edit_url,
            ),
        ),
        name="children_relation",
        title=_("Children"),
        description=Literal(
            _(
                """
                <div class="help-block">
                    <p>The ordered children elements.</p>
                    <hr>
                </div>
                """
            ),
        ),
        candidates=colander.deferred(partial(treeitems, only_groups=only_groups)),
        validator=children_validator,
        widget=ChildrenWidget(child_input_name="treeitem_id", add_subitem=True, orderable=True),
    )
Example #4
0
class BookSchema(colander.MappingSchema):
    title = colander.SchemaNode(colander.String())
    author = colander.SchemaNode(colander.String())
    date_published = colander.SchemaNode(
        colander.Date(),
        validator=colander.Range(
            max=date.today(), max_err='Book can\' be published in the future'))
    chapters = colander.SequenceSchema(ChapterSchema())
Example #5
0
class ThemesOrderingSchema(colander.MappingSchema):
    themes = colander.SequenceSchema(
        ThemeOrderSchema(Theme,
                         includes=['id', 'ordering'],
                         name='theme',
                         widget=ThemeOrderWidget()),
        name='themes',
        treeitems=treeitems,
        validator=themes_validator,
        widget=ChildrenWidget(add_subitem=False, category='structural'))
Example #6
0
class CreateAdminGroupSchema(CSRFSchema):

    group_type = colander.SchemaNode(
        colander.String(),
        title=_('Group Type'),
        widget=SelectWidget(values=(('', _('Select')), ) + VALID_GROUP_TYPES),
        validator=group_type_validator,
    )

    name = colander.SchemaNode(
        colander.String(),
        title=_('Group Name'),
        validator=validators.Length(min=GROUP_NAME_MIN_LENGTH,
                                    max=GROUP_NAME_MAX_LENGTH),
    )

    authority = colander.SchemaNode(
        colander.String(),
        title=_('Authority'),
        description=_("The group's authority"),
        hint=_('The authority within which this group should be created.'
               ' Note that only users within the designated authority'
               ' will be able to be associated with this group (as'
               ' creator or member).'))

    creator = colander.SchemaNode(
        colander.String(),
        title=_('Creator'),
        description=_("Username for this group's creator"),
        hint=_(
            'This user will be set as the "creator" of the group. Note that'
            ' the user must be on the same authority as the group authority'),
    )

    description = colander.SchemaNode(
        colander.String(),
        title=_('Description'),
        description=_('Optional group description'),
        validator=colander.Length(max=GROUP_DESCRIPTION_MAX_LENGTH),
        widget=TextAreaWidget(rows=3),
        missing=None)

    origins = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(colander.String(),
                            name='origin',
                            validator=colander.url),
        title=_('Scope Origins'),
        hint=_(
            'Origins where this group appears (e.g. "https://example.com")'),
        widget=SequenceWidget(add_subitem_text_template=_('Add origin'),
                              min_len=1),
        validator=colander.Length(
            min=1, min_err=_('At least one origin must be specified')))
Example #7
0
class ThemesOrderingSchema(colander.MappingSchema):
    themes = colander.SequenceSchema(
        ThemeOrderSchema(Theme,
                         includes=["id", "ordering"],
                         name="theme",
                         widget=ThemeOrderWidget()),
        name="themes",
        treeitems=treeitems,
        validator=themes_validator,
        widget=ChildrenWidget(add_subitem=False, category="structural"),
    )
Example #8
0
def children_schema_node(only_groups=False):
    return colander.SequenceSchema(
        ChildSchemaNode(LayergroupTreeitem,
                        name="layergroup_treeitem",
                        widget=ChildWidget()),
        name="children_relation",
        title=_("Children"),
        treeitems=colander.deferred(partial(treeitems,
                                            only_groups=only_groups)),
        validator=children_validator,
        widget=ChildrenWidget(category="structural"),
    )
Example #9
0
class ContainerSchema(colander.MappingSchema):
    id_container = colander.SchemaNode(colander.String(), missing='')
    id_view = colander.SchemaNode(colander.String())
    type = colander.SchemaNode(colander.String(), missing='generic')
    description = colander.SchemaNode(colander.String(), missing='')
    x = colander.SchemaNode(colander.Integer(), missing=0)
    y = colander.SchemaNode(colander.Integer(), missing=0)
    width = colander.SchemaNode(colander.Integer(), missing=2)
    height = colander.SchemaNode(colander.Integer(), missing=2)
    z = colander.SchemaNode(colander.Integer(), missing=0)
    data = colander.SchemaNode(colander.String(), missing=None)
    item_ids = colander.SequenceSchema(SchemaNode(String()), missing=[])
Example #10
0
def dimensions_schema_node(
        prop: InstrumentedAttribute) -> colander.SequenceSchema:
    """Get the scheme of the dimensions."""
    return colander.SequenceSchema(
        GeoFormSchemaNode(Dimension,
                          name="dimension",
                          widget=MappingWidget(template="dimension")),
        name=prop.key,
        title=prop.info["colanderalchemy"]["title"],
        description=prop.info["colanderalchemy"]["description"],
        widget=SequenceWidget(category="structural", template="dimensions"),
    )
Example #11
0
def functionalities_schema_node(
        prop: InstrumentedAttribute,
        model: DeclarativeMeta) -> colander.SequenceSchema:
    """Get the schema of the functionalities."""

    return colander.SequenceSchema(
        GeoFormManyToManySchemaNode(Functionality),
        name=prop.key,
        title=prop.info["colanderalchemy"]["title"],
        description=prop.info["colanderalchemy"].get("description"),
        widget=functionalities_widget(model),
        validator=manytomany_validator,
        missing=colander.drop,
    )
Example #12
0
def roles_schema_node(name):
    return colander.SequenceSchema(
        GeoFormManyToManySchemaNode(Role),
        name=name,
        widget=RelationCheckBoxListWidget(
            Role,
            "id",
            "name",
            order_by="name",
            edit_url=lambda request, value: request.route_url(
                "c2cgeoform_item", table="roles", id=value),
        ),
        validator=manytomany_validator,
        missing=colander.drop,
    )
Example #13
0
def roles_schema_node(prop: InstrumentedAttribute) -> colander.SequenceSchema:
    """Get the schema of all the items."""
    return colander.SequenceSchema(
        GeoFormManyToManySchemaNode(Role),
        name=prop.key,
        title=prop.info["colanderalchemy"]["title"],
        description=prop.info["colanderalchemy"].get("description"),
        widget=RelationCheckBoxListWidget(
            Role,
            "id",
            "name",
            order_by="name",
            edit_url=lambda request, value: request.route_url(
                "c2cgeoform_item", table="roles", id=value),
        ),
        validator=manytomany_validator,
        missing=colander.drop,
    )
Example #14
0
    def deserialize(self, cstruct=colander.null):

        # If permissions are not a mapping (e.g null or invalid), try deserializing
        if not isinstance(cstruct, dict):
            return super().deserialize(cstruct)

        # If permissions are listed, check fields and produce fancy error messages
        if self.known_perms:
            for perm in cstruct:
                colander.OneOf(choices=self.known_perms)(self, perm)
            return super().deserialize(cstruct)

        # Else deserialize the fields that are not on the schema
        permissions = {}
        perm_schema = colander.SequenceSchema(
            colander.SchemaNode(colander.String()))
        for perm, principals in cstruct.items():
            permissions[perm] = perm_schema.deserialize(principals)

        return permissions
Example #15
0
class ThemesOrderingSchema(colander.MappingSchema):
    themes = colander.SequenceSchema(
        ThemeOrderSchema(
            Theme,
            includes=["id", "ordering"],
            name="theme",
            widget=ChildWidget(
                input_name="id",
                model=TreeItem,
                label_field="name",
                icon_class=lambda item: "icon-{}".format(item.item_type),
                edit_url=treeitem_edit_url,
            ),
        ),
        name="themes",
        candidates=themes,
        validator=themes_validator,
        widget=ChildrenWidget(child_input_name="id",
                              add_subitem=False,
                              orderable=True),
    )
Example #16
0
    def deserialize(self, cstruct=colander.null):
        # If permissions are not a mapping (e.g null or invalid), try deserializing
        if not isinstance(cstruct, dict):
            return super().deserialize(cstruct)

        # If using application/merge-patch+json we need to allow null values as they
        # represent removing a key.
        cstruct, removed_keys = self._preprocess_null_perms(cstruct)

        # If permissions are listed, check fields and produce fancy error messages
        if self.known_perms:
            for perm in cstruct:
                colander.OneOf(choices=self.known_perms)(self, perm)
            permissions = super().deserialize(cstruct)

        # Else deserialize the fields that are not on the schema
        else:
            permissions = {}
            perm_schema = colander.SequenceSchema(colander.SchemaNode(colander.String()))
            for perm, principals in cstruct.items():
                permissions[perm] = perm_schema.deserialize(principals)

        return self._postprocess_null_perms(permissions, removed_keys)
Example #17
0
def children_schema_node(only_groups=False):
    return colander.SequenceSchema(
        ChildSchemaNode(
            LayergroupTreeitem,
            name="layergroup_treeitem",
            widget=ChildWidget(
                input_name="treeitem_id",
                model=TreeItem,
                label_field="name",
                icon_class=lambda treeitem: "icon-{}".format(treeitem.item_type
                                                             ),
                edit_url=treeitem_edit_url,
            ),
        ),
        name="children_relation",
        title=_("Children"),
        candidates=colander.deferred(
            partial(treeitems, only_groups=only_groups)),
        validator=children_validator,
        widget=ChildrenWidget(child_input_name="treeitem_id",
                              add_subitem=True,
                              orderable=True),
    )
Example #18
0
class CreateAdminGroupSchema(CSRFSchema):
    def __init__(self, *args):
        super(CreateAdminGroupSchema, self).__init__(
            validator=group_creator_validator, *args
        )

    group_type = colander.SchemaNode(
        colander.String(),
        title=_("Group Type"),
        widget=SelectWidget(values=(("", _("Select")),) + VALID_GROUP_TYPES),
        validator=group_type_validator,
    )

    name = colander.SchemaNode(
        colander.String(),
        title=_("Group Name"),
        validator=validators.Length(
            min=GROUP_NAME_MIN_LENGTH, max=GROUP_NAME_MAX_LENGTH
        ),
        widget=TextInputWidget(max_length=GROUP_NAME_MAX_LENGTH),
    )

    organization = colander.SchemaNode(
        colander.String(),
        title=_("Organization"),
        description=_("Organization which this group belongs to"),
        widget=group_organization_select_widget,
    )

    creator = colander.SchemaNode(
        colander.String(),
        title=_("Creator"),
        description=_("Username for this group's creator"),
        hint=_(
            'This user will be set as the "creator" of the group. Note that'
            " the user must be on the same authority as the group authority"
        ),
    )

    description = colander.SchemaNode(
        colander.String(),
        title=_("Description"),
        description=_("Optional group description"),
        validator=colander.Length(max=GROUP_DESCRIPTION_MAX_LENGTH),
        widget=TextAreaWidget(rows=3, max_length=GROUP_DESCRIPTION_MAX_LENGTH),
        missing=None,
    )

    # Although the default value of the enforce_scope property is True,
    # we need to allow the unchecking of the checkbox that represents it,
    # which means that empty values should be treated as False.
    enforce_scope = colander.SchemaNode(
        colander.Boolean(),
        hint=_(
            "Only allow annotations for documents within this group's defined scopes"
        ),
        widget=CheckboxWidget(css_class="form-checkbox--inline"),
        missing=False,
    )

    scopes = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(
            colander.String(), name="scope", validator=url_with_origin_validator
        ),
        title=_("Scopes"),
        hint=_(
            "Define where this group appears. A document's URL must start with one or more"
            " of the entered scope strings (e.g. 'http://www.example.com')"
        ),
        widget=SequenceWidget(add_subitem_text_template=_("Add scope"), min_len=1),
        validator=colander.Length(
            min=1, min_err=_("At least one scope must be specified")
        ),
    )

    members = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(
            colander.String(), name="member", validator=member_exists_validator
        ),
        title=_("Members"),
        hint=_("Add more members by their username to this group"),
        widget=SequenceWidget(add_subitem_text_template=_("Add member")),
        missing=None,
    )
from c2cgeoform.ext.deform_ext import RelationCheckBoxListWidget
from c2cgeoform.schema import GeoFormManyToManySchemaNode, manytomany_validator
import colander

from c2cgeoportal_admin import _
from c2cgeoportal_commons.models.main import RestrictionArea

restrictionareas_schema_node = colander.SequenceSchema(
    GeoFormManyToManySchemaNode(RestrictionArea),
    name="restrictionareas",
    title=_("Restriction areas"),
    widget=RelationCheckBoxListWidget(
        RestrictionArea,
        "id",
        "name",
        order_by="name",
        edit_url=lambda request, value: request.route_url(
            "c2cgeoform_item", table="restriction_areas", id=value),
    ),
    validator=manytomany_validator,
    missing=colander.drop,
)
Example #20
0
from c2cgeoform.ext.deform_ext import RelationCheckBoxListWidget
from c2cgeoform.views.abstract_views import AbstractViews, ListField

from ..models.c2cgeoform_demo import Excavation, Situation

_list_field = partial(ListField, Excavation)

base_schema = GeoFormSchemaNode(Excavation)
base_schema.add_before(
    'contact_persons',
    colander.SequenceSchema(
        GeoFormManyToManySchemaNode(Situation),
        name='situations',
        title='Situations',
        widget=RelationCheckBoxListWidget(
            Situation,
            'id',
            'name',
            order_by='name'
        ),
        validator=manytomany_validator
    )
)
base_schema.add_unique_validator(Excavation.reference_number, Excavation.hash)


@view_defaults(match_param='table=excavations')
class ExcavationViews(AbstractViews):

    _model = Excavation
    _base_schema = base_schema
    _id_field = 'hash'
Example #21
0
class BookListSchema(colander.MappingSchema):
    name = colander.SchemaNode(colander.String())
    books = colander.SequenceSchema(
        BookSchema(),
        validator=colander.Length(min=2,
                                  min_err='You need at least ${min} books'))
Example #22
0
class BatchResponseBodySchema(colander.MappingSchema):
    responses = colander.SequenceSchema(
        BatchResponseSchema(missing=colander.drop))
Example #23
0
class CreateAdminGroupSchema(CSRFSchema):
    def __init__(self, *args):
        super(CreateAdminGroupSchema,
              self).__init__(validator=group_creator_validator, *args)

    group_type = colander.SchemaNode(
        colander.String(),
        title=_('Group Type'),
        widget=SelectWidget(values=(('', _('Select')), ) + VALID_GROUP_TYPES),
        validator=group_type_validator,
    )

    name = colander.SchemaNode(
        colander.String(),
        title=_('Group Name'),
        validator=validators.Length(min=GROUP_NAME_MIN_LENGTH,
                                    max=GROUP_NAME_MAX_LENGTH),
        widget=TextInputWidget(max_length=GROUP_NAME_MAX_LENGTH),
    )

    organization = colander.SchemaNode(
        colander.String(),
        title=_('Organization'),
        description=_('Organization which this group belongs to'),
        widget=group_organization_select_widget,
    )

    creator = colander.SchemaNode(
        colander.String(),
        title=_('Creator'),
        description=_("Username for this group's creator"),
        hint=_(
            'This user will be set as the "creator" of the group. Note that'
            ' the user must be on the same authority as the group authority'),
    )

    description = colander.SchemaNode(
        colander.String(),
        title=_('Description'),
        description=_('Optional group description'),
        validator=colander.Length(max=GROUP_DESCRIPTION_MAX_LENGTH),
        widget=TextAreaWidget(rows=3, max_length=GROUP_DESCRIPTION_MAX_LENGTH),
        missing=None)

    origins = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(colander.String(),
                            name='origin',
                            validator=colander.url),
        title=_('Scope Origins'),
        hint=_(
            'Origins where this group appears (e.g. "https://example.com")'),
        widget=SequenceWidget(add_subitem_text_template=_('Add origin'),
                              min_len=1),
        validator=colander.Length(
            min=1, min_err=_('At least one origin must be specified')))

    members = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(colander.String(),
                            name='member',
                            validator=member_exists_validator),
        title=_('Members'),
        hint=_('Add more members by their username to this group'),
        widget=SequenceWidget(add_subitem_text_template=_('Add member')),
        missing=None)
Example #24
0
 def body(node, kwargs):
     resource = kwargs.get('record')['data']
     collection = colander.MappingSchema()
     collection['data'] = colander.SequenceSchema(resource, missing=[])
     return collection
Example #25
0
        "icon_class": "icon-{}".format(layer.item_type),
        "edit_url": treeitem_edit_url(kw["request"], layer),
        "group": "All",
    } for layer in query]


base_schema.add(
    colander.SequenceSchema(
        GeoFormManyToManySchemaNode(
            Layer,
            name="layer",
            includes=["id"],
            widget=ChildWidget(
                input_name="id",
                model=Layer,
                label_field="name",
                icon_class=lambda layer: "icon-{}".format(layer.item_type),
                edit_url=treeitem_edit_url,
            ),
        ),
        name="layers",
        title=_("Layers"),
        candidates=colander.deferred(layers),
        widget=ChildrenWidget(child_input_name="id", orderable=False),
    ))


@view_defaults(match_param="table=restriction_areas")
class RestrictionAreaViews(AbstractViews):
    _list_fields = [
        _list_field("id"),
        _list_field("name"),
Example #26
0
        dict_['value'] = dict_[self._ui_type(dict_['name'])]
        return super().objectify(dict_, context)

    def dictify(self, obj):
        dict_ = super().dictify(obj)
        value = obj.value or colander.null
        # depending on the type set the value in the right widget
        dict_[self._ui_type(obj.name)] = value
        return dict_

    def _ui_type(self, metadata_name):
        # pylint: disable=unsubscriptable-object
        metadata_type = self.metadata_definitions[metadata_name].get(
            'type', 'string')
        return metadata_type if metadata_type in self.available_types else 'string'


metadatas_schema_node = colander.SequenceSchema(
    MetadataSchemaNode(Metadata,
                       name='metadata',
                       metadata_definitions=metadata_definitions,
                       validator=regex_validator,
                       widget=MappingWidget(template='metadata'),
                       overrides={'name': {
                           'widget': metadata_name_widget
                       }}),
    name='metadatas',
    title=_('Metadatas'),
    metadata_definitions=metadata_definitions,
    widget=SequenceWidget(template='metadatas', category='structural'))
Example #27
0
class UserSchema(colander.MappingSchema):
    userid = stringish()
    first_name = stringish()
    last_name = stringish()
    groups = colander.SequenceSchema(stringish())
Example #28
0
        for user in query
    ]


base_schema.add(
    colander.SequenceSchema(
        GeoFormManyToManySchemaNode(
            User,
            name="layer",
            includes=["id"],
            widget=ChildWidget(
                input_name="id",
                model=User,
                label_field="username",
                icon_class=lambda user: "******",
                edit_url=lambda request, user: request.route_url(
                    "c2cgeoform_item",
                    table="users",
                    id=user.id,
                ),
            ),
        ),
        name="users",
        title=_("Users"),
        candidates=colander.deferred(users),
        widget=ChildrenWidget(child_input_name="id", orderable=False, category="structural"),
    )
)


@view_defaults(match_param="table=roles")
class RoleViews(AbstractViews):
Example #29
0
 def body(node, kwargs):
     resource = kwargs.get("record")["data"]
     collection = colander.MappingSchema()
     collection["data"] = colander.SequenceSchema(resource, missing=[])
     return collection
Example #30
0
    def dictify(self, obj):
        dict_ = super().dictify(obj)
        value = obj.value or colander.null
        # depending on the type set the value in the right widget
        dict_[self._ui_type(obj.name)] = value
        return dict_

    def _ui_type(self, metadata_name):
        # pylint: disable=unsubscriptable-object
        metadata_type = self.metadata_definitions[metadata_name].get(
            "type", "string")
        return metadata_type if metadata_type in self.available_types else "string"


metadatas_schema_node = colander.SequenceSchema(
    MetadataSchemaNode(
        Metadata,
        name="metadata",
        metadata_definitions=metadata_definitions,
        validator=regex_validator,
        widget=MappingWidget(template="metadata"),
        overrides={"name": {
            "widget": metadata_name_widget
        }},
    ),
    name="metadatas",
    title=_("Metadatas"),
    metadata_definitions=metadata_definitions,
    widget=SequenceWidget(template="metadatas", category="structural"),
)