简体   繁体   English

Python:安全地呈现用户输入的 html 代码

[英]Python: Safely render user entered html code

In my Python/Flask application, I would like to safely accept user input and then render it on another page.在我的 Python/Flask 应用程序中,我想安全地接受用户输入,然后将其呈现在另一个页面上。 Something similar to what is done on this website (ref - https://meta.stackexchange.com/questions/1777/what-html-tags-are-allowed-on-stack-exchange-sites ).类似于本网站上所做的事情(参考 - https://meta.stackexchange.com/questions/1777/what-html-tags-are-allowed-on-stack-exchange-sites )。

Is there a python library to properly sanitize such input, or else is there some simple way to do it?是否有 python 库来正确清理此类输入,或者有一些简单的方法可以做到吗?

Take a look at bleach by Mozilla.看看 Mozilla 的bleach

Example例子

import bleach
html = """
<h1> Page Title </h1>
<script> alert("Boom!")</script>
"""
allowed_tags = [
    'a', 'abbr', 'acronym', 'b', 'blockquote', 'br',
    'code', 'dd', 'del', 'div', 'dl', 'dt', 'em',
    'em', 'h1', 'h2', 'h3', 'hr', 'i', 'img', 'li',
    'ol', 'p', 'pre', 's', 'strong', 'sub', 'sup',
    'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul'
]
# Attributes deemed safe
allowed_attrs = {
    '*': ['class'],
    'a': ['href', 'rel'],
    'img': ['src', 'alt']
}
# Sanitize the html using bleach &
# Convert text links to actual links
html_sanitized = bleach.clean(
    html,
    tags=allowed_tags,
    attributes=allowed_attrs
)
print(html_sanitized)

Output Output

<h1> Page Title </h1>
&lt;script&gt; alert("Boom!")&lt;/script&gt;

I have used it in an example app for my flask extension (Flask-MDE).我已经在我的 flask 扩展(Flask-MDE)的示例应用程序中使用了它。 Feel free to check that out here .随时在这里查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM