带漂白剂的Flask和Jinja2,图像HTML不工作

2024-06-02 06:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为自己的一个项目创建一个小博客,只有我,作为用户,可以访问发布页面。我之前一直在关注一个Flask教程,它的最终产品使您能够发布HTML并通过Jinja2模板传递它,使用漂白剂和Markdown。在

在我的models.py文件中,这些是允许的标记。在

@staticmethod

def on_changed_body(target, value, oldvalue, initiator):
    allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
                    'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
                    'h1', 'h2', 'h3', 'p', 'img', 'video', 'div', 'iframe', 'p', 'br', 'span', 'hr', 'src', 'class']
    target.body_html = bleach.linkify(bleach.clean(
        markdown(value, output_format='html'),
        tags=allowed_tags, strip=False))

我添加了一些img和嵌入标签,因为这些对我的博客很重要。我有一个由一些文本和一个图像组成的示例帖子,它被保存到(SQLAlchemy MySQL)数据库中,这正是我编写它的方式。以下是直接从数据库中获取的。在

^{pr2}$

另外,我的blog post表单下面有一个显示HTML预览的字段。图像按预期显示,所以我知道这很好,<marquee></marquee>标记显示为标记。在

在我的模板文件中,我像这样传递body\u html。在

{% if post.body_html %}
    {{ post.body_html | safe }}
{% else %}
    {{ post.body }}
{% endif %}

当我在浏览器中导航到文章时,图像根本不会出现。但是marquee标记显示为<marquee>Bye</marquee>,在开发人员控制台中进一步检查时,<img>标记出现在HTML中,只是没有“src”属性。在

有办法解决这个问题吗?这是金贾的配置吗?如果这是解决方案,有没有一种方法可以声明允许的属性?在

谢谢。在


Tags: 文件标记图像src模板targetimgvalue
1条回答
网友
1楼 · 发布于 2024-06-02 06:45:49

再多一点耐心,再加上一些谷歌搜索,结果就很有成效了,直接从bleach docs上获得:

The attributes kwarg is a whitelist of attributes. It can be a list, in which case the attributes are allowed for any tag, or a dictionary, in which case the keys are tag names (or a wildcard: * for all tags) and the values are lists of allowed attributes.

所以,我在我的漂白剂。清洁models.py中的函数:

 @staticmethod
    def on_changed_body(target, value, oldvalue, initiator):
        allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
                        'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
                        'h1', 'h2', 'h3', 'p', 'img', 'video', 'div', 'iframe', 'p', 'br', 'span', 'hr', 'src', 'class']
        allowed_attrs = {'*': ['class'],
                        'a': ['href', 'rel'],
                        'img': ['src', 'alt']}
        target.body_html = bleach.linkify(bleach.clean(
            markdown(value, output_format='html'),
            tags=allowed_tags, strip=False, attributes=allowed_attrs))

这真是太棒了。我会调整它以适应嵌入。在

相关问题 更多 >