python – 带漂白的Flask和Jinja2,图像HTML不起作用

我一直在为一个项目创建一个小博客,只有我作为用户才能访问发布页面.我之前一直在关注Flask教程,其最终产品使您能够发布HTML并使用漂白和Markdown将其传递给Jinja2模板.

在我的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和embedding标签,因为这些对我的博客很重要.我有一个由一些文本和一个图像组成的示例文章,它正在保存到(SQLAlchemy MySQL)数据库,正是我编写它的方式.以下是直接从数据库中获取的.

<p>Hello</p>

<img src="https://catastrophicfindings.files.wordpress.com/2012/07/moomin-childhood-memories-260482_829_494.jpg">

<marquee>Bye</marquee>

此外,我的博客文章表单下方有一个字段,显示HTML的预览.图像显示为预期,因此我知道这很好,并且< marquee>< / marquee>标签显示为标记.

在我的模板文件中,我正在传递这个body_html.

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

当我在浏览器中导航到帖子时,图像根本不显示.然而,选取框标记显示为< marquee> Bye< / marquee>,并且在开发者控制台中进一步检查时,< img>标签出现在HTML中,只是没有’src’属性.

有没有什么办法解决这一问题?这会是Jinja的配置吗?有没有办法声明允许的属性,如果这是解决方案?

谢谢.

解决方法:

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中的bleach.clean函数中添加了一个所需属性的字典:

 @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))

这非常有效.我将调整它以适应嵌入.

相关文章

markdown语法1、vscode预览md文件打开侧边预览按完Control+K...
这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快...
这加粗样式里写自定义目录标题使用Markdown编辑器新的改变功...
Markdown基本语法标题字体分割线下划线列表列表无序列表使用...
MarkDown学习标题几级标题就加几个井号,最多支持到6级字体H...
markdown基本语法目录:文章目录markdown基本语法1.斜体和粗...