Exemple #1
0
class TopicListingSchema(Schema):
    """Marshmallow schema to validate arguments for a topic listing page."""

    DEFAULT_TOPICS_PER_PAGE = 50

    order = Enum(TopicSortOption)
    period = ShortTimePeriod(allow_none=True)
    after = ID36()
    before = ID36()
    per_page = Integer(
        validate=Range(min=1, max=100),
        missing=DEFAULT_TOPICS_PER_PAGE,
    )
    rank_start = Integer(load_from='n', validate=Range(min=1), missing=None)
    tag = Ltree(missing=None)
    unfiltered = Boolean(missing=False)

    @validates_schema
    def either_after_or_before(self, data: dict) -> None:
        """Fail validation if both after and before were specified."""
        if data.get('after') and data.get('before'):
            raise ValidationError("Can't specify both after and before.")

    @pre_load
    def reset_rank_start_on_first_page(self, data: dict) -> dict:
        """Reset rank_start to 1 if this is a first page (no before/after)."""
        if not (data.get('before') or data.get('after')):
            data['rank_start'] = 1

        return data

    class Meta:
        """Always use strict checking so error handlers are invoked."""

        strict = True
Exemple #2
0
class GroupSchema(Schema):
    """Marshmallow schema for groups."""

    path = Ltree(required=True)
    created_time = DateTime(dump_only=True)
    short_description = SimpleString(
        max_length=SHORT_DESCRIPTION_MAX_LENGTH, allow_none=True
    )
    sidebar_markdown = Markdown(allow_none=True)

    @pre_load
    def prepare_path(self, data: dict, many: bool, partial: Any) -> dict:
        """Prepare the path value before it's validated."""
        # pylint: disable=unused-argument
        if not self.context.get("fix_path_capitalization"):
            return data

        if "path" not in data or not isinstance(data["path"], str):
            return data

        new_data = data.copy()

        new_data["path"] = new_data["path"].lower()

        return new_data

    @validates("path")
    def validate_path(self, value: sqlalchemy_utils.Ltree) -> None:
        """Validate the path field, raising an error if an issue exists."""
        # check each element for length and against validity regex
        path_elements = value.path.split(".")
        for element in path_elements:
            if len(element) > 256:
                raise ValidationError("Path element %s is too long" % element)

            if not GROUP_PATH_ELEMENT_VALID_REGEX.match(element):
                raise ValidationError("Path element %s is invalid" % element)

    @pre_load
    def prepare_sidebar_markdown(self, data: dict, many: bool, partial: Any) -> dict:
        """Prepare the sidebar_markdown value before it's validated."""
        # pylint: disable=unused-argument
        if "sidebar_markdown" not in data:
            return data

        new_data = data.copy()

        # if the value is empty, convert it to None
        if not new_data["sidebar_markdown"] or new_data["sidebar_markdown"].isspace():
            new_data["sidebar_markdown"] = None

        return new_data
Exemple #3
0
class GroupSchema(Schema):
    """Marshmallow schema for groups."""

    path = Ltree(required=True, load_from="group_path")
    created_time = DateTime(dump_only=True)
    short_description = SimpleString(max_length=SHORT_DESCRIPTION_MAX_LENGTH,
                                     allow_none=True)
    sidebar_markdown = Markdown(allow_none=True)

    @pre_load
    def prepare_path(self, data: dict) -> dict:
        """Prepare the path value before it's validated."""
        if not self.context.get("fix_path_capitalization"):
            return data

        # path can also be loaded from group_path, so we need to check both
        keys = ("path", "group_path")

        for key in keys:
            if key in data and isinstance(data[key], str):
                data[key] = data[key].lower()

        return data

    @validates("path")
    def validate_path(self, value: sqlalchemy_utils.Ltree) -> None:
        """Validate the path field, raising an error if an issue exists."""
        # check each element for length and against validity regex
        path_elements = value.path.split(".")
        for element in path_elements:
            if len(element) > 256:
                raise ValidationError("Path element %s is too long" % element)

            if not GROUP_PATH_ELEMENT_VALID_REGEX.match(element):
                raise ValidationError("Path element %s is invalid" % element)

    @pre_load
    def prepare_sidebar_markdown(self, data: dict) -> dict:
        """Prepare the sidebar_markdown value before it's validated."""
        if "sidebar_markdown" not in data:
            return data

        # if the value is empty, convert it to None
        if not data["sidebar_markdown"] or data["sidebar_markdown"].isspace():
            data["sidebar_markdown"] = None

        return data

    class Meta:
        """Always use strict checking so error handlers are invoked."""

        strict = True
Exemple #4
0
class TopicListingSchema(PaginatedListingSchema):
    """Marshmallow schema to validate arguments for a topic listing page."""

    period = ShortTimePeriod(allow_none=True)
    order = Enum(TopicSortOption)
    tag = Ltree(missing=None)
    unfiltered = Boolean(missing=False)
    rank_start = Integer(load_from="n", validate=Range(min=1), missing=None)

    @pre_load
    def reset_rank_start_on_first_page(self, data: dict) -> dict:
        """Reset rank_start to 1 if this is a first page (no before/after)."""
        if not (data.get("before") or data.get("after")):
            data["rank_start"] = 1

        return data
Exemple #5
0
class TopicListingSchema(PaginatedListingSchema):
    """Marshmallow schema to validate arguments for a topic listing page."""

    period = ShortTimePeriod(allow_none=True)
    order = Enum(TopicSortOption, missing=None)
    tag = Ltree(missing=None)
    unfiltered = Boolean(missing=False)
    rank_start = Integer(data_key="n", validate=Range(min=1), missing=None)

    @pre_load
    def reset_rank_start_on_first_page(
        self, data: dict, many: bool, partial: Any
    ) -> dict:
        """Reset rank_start to 1 if this is a first page (no before/after)."""
        # pylint: disable=unused-argument
        if "rank_start" not in self.fields:
            return data

        if not (data.get("before") or data.get("after")):
            data["n"] = 1

        return data
Exemple #6
0
class TopicSchema(Schema):
    """Marshmallow schema for topics."""

    topic_id36 = ID36()
    title = SimpleString(max_length=TITLE_MAX_LENGTH)
    topic_type = Enum(dump_only=True)
    markdown = Markdown(allow_none=True)
    rendered_html = String(dump_only=True)
    link = URL(schemes={'http', 'https'}, allow_none=True)
    created_time = DateTime(dump_only=True)
    tags = List(Ltree())

    user = Nested(UserSchema, dump_only=True)
    group = Nested(GroupSchema, dump_only=True)

    @pre_load
    def prepare_tags(self, data: dict) -> dict:
        """Prepare the tags before they're validated."""
        if 'tags' not in data:
            return data

        tags: typing.List[str] = []

        for tag in data['tags']:
            tag = tag.lower()

            # replace spaces with underscores
            tag = tag.replace(' ', '_')

            # remove any consecutive underscores
            tag = re.sub('_{2,}', '_', tag)

            # remove any leading/trailing underscores
            tag = tag.strip('_')

            # drop any empty tags
            if not tag or tag.isspace():
                continue

            # skip any duplicate tags
            if tag in tags:
                continue

            tags.append(tag)

        data['tags'] = tags

        return data

    @validates('tags')
    def validate_tags(
        self,
        value: typing.List[sqlalchemy_utils.Ltree],
    ) -> None:
        """Validate the tags field, raising an error if an issue exists.

        Note that tags are validated by ensuring that each tag would be a valid
        group path. This is definitely mixing concerns, but it's deliberate in
        this case. It will allow for some interesting possibilities by ensuring
        naming "compatibility" between groups and tags. For example, a popular
        tag in a group could be converted into a sub-group easily.
        """
        group_schema = GroupSchema(partial=True)
        for tag in value:
            try:
                group_schema.validate({'path': tag})
            except ValidationError:
                raise ValidationError('Tag %s is invalid' % tag)

    @pre_load
    def prepare_markdown(self, data: dict) -> dict:
        """Prepare the markdown value before it's validated."""
        if 'markdown' not in data:
            return data

        # if the value is empty, convert it to None
        if not data['markdown'] or data['markdown'].isspace():
            data['markdown'] = None

        return data

    @pre_load
    def prepare_link(self, data: dict) -> dict:
        """Prepare the link value before it's validated."""
        if 'link' not in data:
            return data

        # if the value is empty, convert it to None
        if not data['link'] or data['link'].isspace():
            data['link'] = None
            return data

        # prepend http:// to the link if it doesn't have a scheme
        parsed = urlparse(data['link'])
        if not parsed.scheme:
            data['link'] = 'http://' + data['link']

        return data

    @validates_schema
    def link_or_markdown(self, data: dict) -> None:
        """Fail validation unless at least one of link or markdown were set."""
        if 'link' not in data and 'markdown' not in data:
            return

        link = data.get('link')
        markdown = data.get('markdown')

        if not (markdown or link):
            raise ValidationError(
                'Topics must have either markdown or a link.')

    class Meta:
        """Always use strict checking so error handlers are invoked."""

        strict = True
Exemple #7
0
class TopicSchema(Schema):
    """Marshmallow schema for topics."""

    topic_id36 = ID36()
    title = SimpleString(max_length=TITLE_MAX_LENGTH)
    topic_type = Enum(dump_only=True)
    markdown = Markdown(allow_none=True)
    rendered_html = String(dump_only=True)
    link = URL(schemes={"http", "https"}, allow_none=True)
    created_time = DateTime(dump_only=True)
    tags = List(Ltree())

    user = Nested(UserSchema, dump_only=True)
    group = Nested(GroupSchema, dump_only=True)

    @pre_load
    def prepare_tags(self, data: dict) -> dict:
        """Prepare the tags before they're validated."""
        if "tags" not in data:
            return data

        tags: typing.List[str] = []

        for tag in data["tags"]:
            tag = tag.lower()

            # replace spaces with underscores
            tag = tag.replace(" ", "_")

            # remove any consecutive underscores
            tag = re.sub("_{2,}", "_", tag)

            # remove any leading/trailing underscores
            tag = tag.strip("_")

            # drop any empty tags
            if not tag or tag.isspace():
                continue

            # handle synonyms
            for name, synonyms in TAG_SYNONYMS.items():
                if tag in synonyms:
                    tag = name

            # skip any duplicate tags
            if tag in tags:
                continue

            tags.append(tag)

        data["tags"] = tags

        return data

    @validates("tags")
    def validate_tags(self, value: typing.List[sqlalchemy_utils.Ltree]) -> None:
        """Validate the tags field, raising an error if an issue exists.

        Note that tags are validated by ensuring that each tag would be a valid group
        path. This is definitely mixing concerns, but it's deliberate in this case. It
        will allow for some interesting possibilities by ensuring naming "compatibility"
        between groups and tags. For example, a popular tag in a group could be
        converted into a sub-group easily.
        """
        group_schema = GroupSchema(partial=True)
        for tag in value:
            try:
                group_schema.validate({"path": str(tag)})
            except ValidationError:
                raise ValidationError("Tag %s is invalid" % tag)

    @pre_load
    def prepare_markdown(self, data: dict) -> dict:
        """Prepare the markdown value before it's validated."""
        if "markdown" not in data:
            return data

        # if the value is empty, convert it to None
        if not data["markdown"] or data["markdown"].isspace():
            data["markdown"] = None

        return data

    @pre_load
    def prepare_link(self, data: dict) -> dict:
        """Prepare the link value before it's validated."""
        if "link" not in data:
            return data

        # if the value is empty, convert it to None
        if not data["link"] or data["link"].isspace():
            data["link"] = None
            return data

        # prepend http:// to the link if it doesn't have a scheme
        parsed = urlparse(data["link"])
        if not parsed.scheme:
            data["link"] = "http://" + data["link"]

        # run the link through the url-transformation process
        data["link"] = apply_url_transformations(data["link"])

        return data

    @validates_schema
    def link_or_markdown(self, data: dict) -> None:
        """Fail validation unless at least one of link or markdown were set."""
        if "link" not in data and "markdown" not in data:
            return

        link = data.get("link")
        markdown = data.get("markdown")

        if not (markdown or link):
            raise ValidationError("Topics must have either markdown or a link.")

    class Meta:
        """Always use strict checking so error handlers are invoked."""

        strict = True