Python Markdown
Converting with the markdown package, extensions, and sanitising the output.
Key PointsMarkdown output is raw HTML — if the source is user-supplied you must sanitise it before rendering.
Basic Conversion
The markdown package converts text to an HTML fragment. Tables, highlighting and TOC need explicit extensions.
Bash
pip install markdownPython
import markdown
text = """
# 标题
**粗体** 和 `code`
| 语言 | 课数 |
|---|---|
| Python | 60 |
"""
html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"])
print(html)Output
<h1 id="_1">标题</h1>
<p><strong>粗体</strong> 和 <code>code</code></p>
<table>
<thead>
<tr><th>语言</th><th>课数</th></tr>
</thead>
<tbody>
<tr><td>Python</td><td>60</td></tr>
</tbody>
</table>Useful Extensions
| Extension | Adds |
|---|---|
| tables | Pipe tables |
| fenced_code | ``` code blocks |
| codehilite | Syntax highlighting classes |
| toc | Heading ids and a TOC |
| nl2br | Newline becomes <br> |
Sanitising
Markdown allows raw HTML, so users can inject <script>. Sanitise before rendering — bleach is the usual choice.
Python
import bleach
import markdown
raw = markdown.markdown("<script>alert(1)</script>**hi**")
safe = bleach.clean(raw, tags=["p", "strong", "em", "code", "pre", "table", "tr", "td", "th"])
print(safe)Output
<p><script>alert(1)</script><strong>hi</strong></p>Use raw
markdown only for trusted content. Any user input must pass through bleach.clean().基础转换
markdown 包把 Markdown 文本转成 HTML 片段。默认不认表格、代码高亮和目录,需要显式开启扩展。
Bash
pip install markdownPython
import markdown
text = """
# 标题
**粗体** 和 `code`
| 语言 | 课数 |
|---|---|
| Python | 60 |
"""
html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"])
print(html)Output
<h1 id="_1">标题</h1>
<p><strong>粗体</strong> 和 <code>code</code></p>
<table>
<thead>
<tr><th>语言</th><th>课数</th></tr>
</thead>
<tbody>
<tr><td>Python</td><td>60</td></tr>
</tbody>
</table>常用扩展
| 扩展 | 作用 |
|---|---|
| tables | 管道表格 |
| fenced_code | ``` 代码块 |
| codehilite | 语法高亮 class |
| toc | 标题锚点与目录 |
| nl2br | 换行变 <br> |
消毒
Markdown 允许内嵌原始 HTML,意味着用户可以注入 <script>。渲染前必须过滤,bleach 是最常用的方案。
Python
import bleach
import markdown
raw = markdown.markdown("<script>alert(1)</script>**hi**")
safe = bleach.clean(raw, tags=["p", "strong", "em", "code", "pre", "table", "tr", "td", "th"])
print(safe)Output
<p><script>alert(1)</script><strong>hi</strong></p>只在自己可信的内容(README、内部文档)上直接用
markdown;任何用户输入都要过 bleach.clean()。