<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>CKEditor &#8211; 李辉 / Grey Li</title>
	<atom:link href="https://greyli.com/tag/ckeditor/feed/" rel="self" type="application/rss+xml" />
	<link>https://greyli.com</link>
	<description>一个编程和写作爱好者的在线记事本</description>
	<lastBuildDate>Thu, 06 Nov 2025 11:36:11 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.9.26</generator>

<image>
	<url>https://greyli.com/wp-content/uploads/2025/03/avatar-500-compressed-144x144.jpg</url>
	<title>CKEditor &#8211; 李辉 / Grey Li</title>
	<link>https://greyli.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>在 Flask-Admin 中集成富文本编辑器 CKEditor</title>
		<link>https://greyli.com/add-ckeditor-in-flask-admin-by-flask-ckeditor/</link>
		<comments>https://greyli.com/add-ckeditor-in-flask-admin-by-flask-ckeditor/#respond</comments>
		<pubDate>Fri, 22 Feb 2019 02:52:25 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[计算机与编程]]></category>
		<category><![CDATA[CKEditor]]></category>
		<category><![CDATA[Flask-Admin]]></category>
		<category><![CDATA[Flask-CKEditor]]></category>
		<category><![CDATA[富文本编辑器]]></category>
		<category><![CDATA[管理后台]]></category>

		<guid isPermaLink="false">http://greyli.com/?p=2310</guid>
		<description><![CDATA[在 Flask-Admin 里，默认使用普通的文本区域（&#60;textarea&#62;）来编辑长文本。借助  [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	在 <a href="https://github.com/flask-admin/flask-admin">Flask-Admin</a> 里，默认使用普通的文本区域（&lt;textarea&gt;）来编辑长文本。借助 <a href="https://github.com/greyli/flask-ckeditor">Flask-CKEditor</a>，你可以很容易的为 Flask-Admin 集成富文本编辑器 <a href="https://ckeditor.com/">CKEditor</a>。
</p>
<p>
	首先安装 Flask-CKEditor：
</p>
<pre>
<code>$ pip install flask-ckeditor</code></pre>
<p>
	下面是一个简单的例子，其中的关键步骤已用注释标出：
</p>
<pre>
<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_ckeditor import CKEditor, CKEditorField  # 导入扩展类 CKEditor 和 字段类 CKEditorField

app = Flask(__name__)
app.config['SECRET_KEY'] = &#39;dev&#39;
app.config['SQLALCHEMY_DATABASE_URI'] = &#39;sqlite:///&#39;

db = SQLAlchemy(app)
ckeditor = CKEditor(app)  # 初始化扩展

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120))
    text = db.Column(db.Text)


# 自定义 Post 模型
class PostAdmin(ModelView):
    form_overrides = dict(text=CKEditorField)  # 重写表单字段，将 text 字段设为 CKEditorField
    create_template = &#39;edit.html&#39;  # 指定创建记录的模板
    edit_template = &#39;edit.html&#39;  # 指定编辑记录的模板

admin = Admin(app, name=&#39;Flask-CKEditor demo&#39;)
admin.add_view(PostAdmin(Post, db.session))

if __name__ == &#39;__main__&#39;:
    app.run(debug=True)</code></pre>
<p>
	在模板文件夹里，我们创建一个 edit.html 文件（templates/edit.html），在这个文件里重载 Flask-Admin 的编辑模板，加载 CKEditor 资源：
</p>
<pre>
<code>{% extends &#39;admin/model/edit.html&#39; %} &lt;!-- 声明继承 Flask-Admin 的模型编辑模板 --&gt;

{% block tail %} &lt;!-- 向父模板的 tail 块内追加内容 --&gt;
    {{ super() }}
    {{ ckeditor.load() }} &lt;!-- 加载 CKEditor 的 JavaScript 文件，默认从 CDN 获取 --&gt;
{% endblock %}</code></pre>
<p>
	实际的效果如下图所示：
</p>
<p>
	<img alt="" class="alignnone size-full wp-image-2344" height="572" src="http://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor.png" width="1203" srcset="https://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor.png 1203w, https://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor-150x71.png 150w, https://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor-300x143.png 300w, https://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor-1024x487.png 1024w, https://greyli.com/wp-content/uploads/2019/02/flask-admin-ckeditor-624x297.png 624w" sizes="(max-width: 1203px) 100vw, 1203px" />
</p>
<p>
	完整的可运行的示例程序代码可以在<a href="http://github.com/greyli/flask-ckeditor/tree/master/examples/flask-admin">这里</a>获取到。
</p>
<p>
	你可以阅读 <a href="https://flask-admin.readthedocs.io/en/latest/">Flask-Admin 文档</a>和 <a href="https://flask-ckeditor.readthedocs.io/en/latest/">Flask-CKEditor 文档</a>了解更多进阶用法。
</p>
<p>
	附注：本文改写自我在 Stack Overflow 上的回答（<a href="https://stackoverflow.com/a/46481343/5511849">https://stackoverflow.com/a/46481343/5511849</a>）。</p>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/add-ckeditor-in-flask-admin-by-flask-ckeditor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>让 CKEditor 图片响应式（responsive）</title>
		<link>https://greyli.com/ckeditor-image-responsive/</link>
		<comments>https://greyli.com/ckeditor-image-responsive/#respond</comments>
		<pubDate>Wed, 12 Dec 2018 09:10:39 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[计算机与编程]]></category>
		<category><![CDATA[CKEditor]]></category>
		<category><![CDATA[响应式]]></category>
		<category><![CDATA[图片]]></category>

		<guid isPermaLink="false">http://greyli.com/?p=2027</guid>
		<description><![CDATA[通过 CKEditor 上传并插入图片后，CKEditor 的图片部件（widget）会在图片的 &#60;im [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	通过 CKEditor 上传并插入图片后，CKEditor 的图片部件（widget）会在图片的 &lt;img&gt; 元素里插入行内样式定义来设置图片的宽高，这会导致响应式布局失效：图片因为被固定了宽高，在窗口缩小后会超出外层元素。生成的 HTML 代码示例如下：
</p>
<pre>
&lt;img alt=&quot;hello&quot; src=&quot;/images/hello.jpg&quot; <strong>style=&quot;height:300px; width:500px&quot;</strong> /&gt;</pre>
<p>
	对于这个问题，有三种解决方法：
</p>
<h2>
	方法 1：设置 CSS<br />
</h2>
<p>
	最简单的解决方法是在 CSS 文件里加入下面的代码：
</p>
<pre>
img {
    max-width: 100%;
    height: auto !important;
}</pre>
<p>
	这会重写 CKEditor 生成的行内 CSS。
</p>
<h2>
	方法 2：使用插件&nbsp;Enhanced Image<br />
</h2>
<p>
	你可以使用加强版的图片部件插件&nbsp;<a href="https://ckeditor.com/cke4/addon/image2">Enhanced Image</a>（Image2）来替代原有的图片部件，同时确保 CKEditor 的版本大于 4.3。
</p>
<p>
	（未测试。）
</p>
<h2>
	方法 3：使用 JavaScript<br />
</h2>
<p>
	如果你使用 Bootstrap，这里还有另一种方法：
</p>
<pre>
CKEDITOR.on(&#39;instanceReady&#39;, function (ev) {
    ev.editor.dataProcessor.htmlFilter.addRules( {
        elements : {
            img: function( el ) {
                // Add bootstrap &quot;img-responsive&quot; class to each inserted image
                el.addClass(&#39;img-responsive&#39;);
        
                // Remove inline &quot;height&quot; and &quot;width&quot; styles and
                // replace them with their attribute counterparts.
                // This ensures that the &#39;img-responsive&#39; class works
                var style = el.attributes.style;
        
                if (style) {
                    // Get the width from the style.
                    var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec(style),
                        width = match &amp;&amp; match[1];
        
                    // Get the height from the style.
                    match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec(style);
                    var height = match &amp;&amp; match[1];
        
                    // Replace the width
                    if (width) {
                        el.attributes.style = el.attributes.style.replace(/(?:^|\s)width\s*:\s*(\d+)px;?/i, &#39;&#39;);
                        el.attributes.width = width;
                    }
        
                    // Replace the height
                    if (height) {
                        el.attributes.style = el.attributes.style.replace(/(?:^|\s)height\s*:\s*(\d+)px;?/i, &#39;&#39;);
                        el.attributes.height = height;
                    }
                }
        
                // Remove the style tag if it is empty
                if (!el.attributes.style)
                    delete el.attributes.style;
            }
        }
    });
});</pre>
<p>
	（<a href="https://gist.github.com/fabiomaggio/c2f4b84756cb4d82c0ae">出处地址</a>）
</p>
<p>
	需要注意的是，如果你使用 Bootstrap 4，需要把第 6 行的 img-responsive 换成 img-fluid。
</p>
<p>
	（未测试。）</p>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/ckeditor-image-responsive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>在 Flask 程序中实现 CKEditor 图片上传和 CSRF 保护</title>
		<link>https://greyli.com/flask-ckeditor-image-upload-csrf/</link>
		<comments>https://greyli.com/flask-ckeditor-image-upload-csrf/#comments</comments>
		<pubDate>Wed, 12 Dec 2018 08:45:01 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[计算机与编程]]></category>
		<category><![CDATA[CKEditor]]></category>
		<category><![CDATA[CSRF]]></category>
		<category><![CDATA[图片上传]]></category>

		<guid isPermaLink="false">http://greyli.com/?p=1981</guid>
		<description><![CDATA[《Flask Web 开发实战》第 2 个实战项目是一个博客（Bluelog），这个项目本来没有添加图片上传支 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	《Flask Web 开发实战》第 2 个实战项目是一个博客（<a href="https://github.com/greyli/bluelog">Bluelog</a>），这个项目本来没有添加图片上传支持，很多人想要自己实现，结果因为项目中同时使用了 CSRFProtect 扩展，它会默认验证所有 POST 请求，进而导致上传图片的请求出错。反馈的人多了，我就做了一些事情来改善这个问题：
</p>
<ul>
<li>
		发布了 <a href="https://github.com/greyli/flask-ckeditor">Flask-CKEditor</a> 0.4.3，内置了对&nbsp;CSRFProtect 扩展的支持。
	</li>
<li>
		在 Bluelog 中实现了图片上传（<a href="https://github.com/greyli/bluelog/commit/7537416ee8320bb81438e34bc6fbe82303c8d441">7537416</a>）。
	</li>
</ul>
<p>
	如果你想实际体验，需要更新本地的 Bluelog 仓库，并更新 Flask-CKEditor 的版本。这篇文章会单独介绍使用 Flask-CKEditor 实现图片上传的方法，顺便说一下新的 CSRF 保护支持。
</p>
<h2>
	基础工作<br />
</h2>
<p>
	使用扩展并不是必须的，但是可以简化大量的工作。这里将通过 <a href="https://github.com/greyli/flask-ckeditor">Flask-CKEditor</a> 来实现相关功能，首先安装（或更新）它：
</p>
<pre>
$ pip install -U Flask-CKEditor</pre>
<p>
	关于创建编辑器输入框等基础内容，可以参考<a href="https://zhuanlan.zhihu.com/p/38643309">这篇文章</a>。
</p>
<h2>
	实现图片上传<br />
</h2>
<p>
	在使用文本编辑器写文章时，上传图片是一个很常见的需求。在CKEditor中，图片上传可以通过<a data-za-detail-view-id="1043" href="https://ckeditor.com/addon/filebrowser" rel="nofollow noreferrer" target="_blank">File Browser</a>插件实现。在服务器端的Flask程序中，你需要做三件事：
</p>
<ol>
<li>
		创建一个视图函数来处理并保存上传文件
	</li>
<li>
		创建一个视图函数来获取图片文件，类似Flask内置的 static 端点
	</li>
<li>
		将配置变量 `CKEDITOR_FILE_UPLOADER` 设为这个视图函数的 URL 或端点值
	</li>
</ol>
<p>
	完整的代码示例如下所示：
</p>
<pre>
from flask_ckeditor import upload_success, upload_fail

app.config['CKEDITOR_FILE_UPLOADER'] = &#39;upload&#39;

@app.route(&#39;/files/&lt;path:filename&gt;&#39;)
def uploaded_files(filename):
    path = &#39;/the/uploaded/directory&#39;
    return send_from_directory(path, filename)

@app.route(&#39;/upload&#39;, methods=['POST'])
def upload():
    f = request.files.get(&#39;upload&#39;)  # 获取上传图片文件对象，键必须为&#39;upload&#39;
    # Add more validations here
    extension = f.filename.split(&#39;.&#39;)[1].lower()
    if extension not in ['jpg', 'gif', 'png', 'jpeg']:  # 验证文件类型示例
        return upload_fail(message=&#39;Image only!&#39;)  # 返回upload_fail调用
    f.save(os.path.join(&#39;/the/uploaded/directory&#39;, f.filename))
    url = url_for(&#39;uploaded_files&#39;, filename=f.filename)
    return upload_success(url=url) # 返回upload_success调用<strong>​</strong></pre>
<p>
	在处理上传文件的视图函数中，你必须返回 `upload_success()`&nbsp;调用，每将 `url` 参数设置为获取上传文件的 URL。通常情况下，除了保存文件，你还需要对上传的图片进行验证和处理（大小、格式、文件名处理等等，具体可以访问这篇<a data-za-detail-view-id="1043" href="https://zhuanlan.zhihu.com/p/23731819">《Flask文件上传（一）：原生实现》</a>了解），在验证未通过时，你需要返回 `upload_fail()` 调用，并使用 `message` 参数传入错误消息。
</p>
<p>
	当设置了 `CKEDITOR_FILE_UPLOADER` 配置变量后，你可以在编辑区域点开图片按钮打开的弹窗中看到一个新的上传标签。另外，你也可以直接将图片文件拖拽到编辑区域进行上传，或复制文件并粘贴到文本区域进行上传（CKEditor &gt;= 4.5）。
</p>
<p>
	<strong>提示</strong> 对应的示例程序在<a data-editable="true" data-offset-key="fqmo6-1-0" href="https://github.com/greyli/flask-ckeditor/tree/master/examples/image-upload" target="_blank">examples/image-upload/</a>目录下。
</p>
<p>
	如果你使用的 CKEditor 版本小于 4.5，则使用下面的方式实现：
</p>
<pre>
from flask import send_from_directory

app.config['CKEDITOR_FILE_UPLOADER'] = &#39;upload&#39;  # this value can be endpoint or url

@app.route(&#39;/files/&lt;filename&gt;&#39;)
def uploaded_files(filename):
    path = &#39;/the/uploaded/directory&#39;
    return send_from_directory(path, filename)

@app.route(&#39;/upload&#39;, methods=['POST'])
@ckeditor.uploader
def upload():
    f = request.files.get(&#39;upload&#39;)
    f.save(os.path.join(&#39;/the/uploaded/directory&#39;, f.filename))
    url = url_for(&#39;uploaded_files&#39;, filename=f.filename)
    return url
</pre>
<h2>
	CSRF 保护<br />
</h2>
<p>
	如果你想为图片上传的请求添加 CSRF 保护，可以通过 CSRFProtect&nbsp;实现（Flask-WTF 内置），首先安装 Flask-WTF：
</p>
<pre>
$ pip install flask-wtf</pre>
<p>
	<strong>同时要确保 Flask-CKEditor 使用了最新版本（0.4.3）</strong>。
</p>
<p>
	然后初始化扩展：
</p>
<pre>
from flask_wtf import CSRFProtect

csrf = CSRFProtect(app) </pre>
<p>
	Flask-CKEditor 0.4.3 版本内置了对 CSRFProtect 的支持，当使用&nbsp;CSRFProtect 时，只需要把配置变量 `CKEDITOR_ENABLE_CSRF` 设为 `True` 即可开启 CSRF 保护：
</p>
<pre>
app.config['CKEDITOR_ENABLE_CSRF'] = True</pre>
<p>
	顺便说一下&nbsp;Flask-CKEditor 内部的实现方式，&nbsp;Flask-CKEditor 需要把 CSRF 令牌放到上传图片的 AJAX 请求首部，这通过 CKEditor 4.9.0 版本新添加的一个配置选项&nbsp;<a href="https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-fileTools_requestHeaders">fileTools_requestHeaders</a>&nbsp;实现，这个配置可以用来想文件上传请求插入自定义的首部字段&nbsp;。所以，如果想要实现 CSRF 保护，CKEditor 的版本需要大于或等于 4.9.0。</p>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/flask-ckeditor-image-upload-csrf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
