Python的Flask框架中集成CKeditor富文本编辑器的教程


Posted in Python onJune 13, 2016

CKeditor是目前最优秀的可见即可得网页编辑器之一,它采用JavaScript编写。具备功能强大、配置容易、跨浏览器、支持多种编程语言、开源等特点。它非常流行,互联网上很容易找到相关技术文档,国内许多WEB项目和大型网站均采用了CKeditor。

下载CKeditor
访问CKeditor官方网站,进入下载页面,选择Standard Package(一般情况下功能足够用了),然后点击Download CKEditor按钮下载ZIP格式的安装文件。如果你想尝试更多的功能,可以选择下载Full Package。

下载好CKeditor之后,解压到Flask项目static/ckeditor目录即可。

在Flask项目中使用CKeditor
在Flask项目中使用CKeditor只需要执行两步就可以了:

在<script>标签引入CKeditor主脚本文件。可以引入本地的文件,也可以引用CDN上的文件。
使用CKEDITOR.replace()把现存的<textarea>标签替换成CKEditor。
示例代码:

<!DOCTYPE html>
<html>
  <head>
    <title>A Simple Page with CKEditor</title>
    <!-- 请确保CKEditor文件路径正确 -->
    <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></script>
  </head>
  <body>
    <form>
      <textarea name="editor1" id="editor1" rows="10" cols="80">
        This is my textarea to be replaced with CKEditor.
      </textarea>
      <script>
        // 用CKEditor替换<textarea id="editor1">
        // 使用默认配置
        CKEDITOR.replace('editor1');
      </script>
    </form>
  </body>
</html>

因为CKeditor足够优秀,所以第二步也可只为<textarea>追加名为ckeditor的class属性值,CKeditor就会自动将其替换。例如:

<!DOCTYPE html>
<html>
  <head>
    <title>A Simple Page with CKEditor</title>
    <!-- 请确保CKEditor文件路径正确 -->
    <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></script>
  </head>
  <body>
    <form>
      <textarea name="editor1" id="editor1" class="ckeditor" rows="10" cols="80">
        This is my textarea to be replaced with CKEditor.
      </textarea>
    </form>
  </body>
</html>

CKEditor脚本文件也可以引用CDN上的文件,下面给出几个参考链接:

<script src="//cdn.ckeditor.com/4.4.6/basic/ckeditor.js"></script>

 基础版(迷你版)

<script src="//cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>

 标准版

<script src="//cdn.ckeditor.com/4.4.6/full/ckeditor.js"></script>

完整版
开启上传功能
默认配置下,CKEditor是没有开启上传功能的,要开启上传功能,也相当的简单,只需要简单修改配置即可。下面来看看几个相关的配置值:

  • filebrowserUploadUrl :文件上传路径。若设置了,则上传按钮会出现在链接、图片、Flash对话窗口。
  • filebrowserImageUploadUrl : 图片上传路径。若不设置,则使用filebrowserUploadUrl值。
  • filebrowserFlashUploadUrl : Flash上传路径。若不设置,则使用filebrowserUploadUrl值。

为了方便,这里我们只设置filebrowserUploadUrl值,其值设为/ckupload/(后面会在Flask中定义这个URL)。

设置配置值主要使用2种方法:

方法1:通过CKEditor根目录的配置文件config.js来设置:

CKEDITOR.editorConfig = function( config ) {
  // ...
  // file upload url
  config.filebrowserUploadUrl = '/ckupload/';
  // ...
};

方法2:将设置值放入作为参数放入CKEDITOR.replace():

<script>
CKEDITOR.replace('editor1', {
  filebrowserUploadUrl: '/ckupload/',
});
</script>

Flask处理上传请求
CKEditor上传功能是统一的接口,即一个接口可以处理图片上传、文件上传、Flash上传。先来看看代码:

def gen_rnd_filename():
  filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route('/ckupload/', methods=['POST'])
def ckupload():
  """CKEditor file upload"""
  error = ''
  url = ''
  callback = request.args.get("CKEditorFuncNum")
  if request.method == 'POST' and 'upload' in request.files:
    fileobj = request.files['upload']
    fname, fext = os.path.splitext(fileobj.filename)
    rnd_name = '%s%s' % (gen_rnd_filename(), fext)
    filepath = os.path.join(app.static_folder, 'upload', rnd_name)
    # 检查路径是否存在,不存在则创建
    dirname = os.path.dirname(filepath)
    if not os.path.exists(dirname):
      try:
        os.makedirs(dirname)
      except:
        error = 'ERROR_CREATE_DIR'
    elif not os.access(dirname, os.W_OK):
      error = 'ERROR_DIR_NOT_WRITEABLE'
    if not error:
      fileobj.save(filepath)
      url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
  else:
    error = 'post error'
  res = """

<script type="text/javascript">
 window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>

""" % (callback, url, error)
  response = make_response(res)
  response.headers["Content-Type"] = "text/html"
  return response

上传文件的获取及保存部分比较简单,是标准的文件上传。这里主要讲讲上传成功后如何回调的问题。

CKEditor文件上传之后,服务端返回HTML文件,HTML文件包含JAVASCRIPT脚本,JS脚本会调用一个回调函数,若无错误,回调函数将返回的URL转交给CKEditor处理。

这3个参数依次是:

  • CKEditorFuncNum : 回调函数序号。CKEditor通过URL参数提交给服务端
  • URL : 上传后文件的URL
  • Error : 错误信息。若无错误,返回空字符串

使用蓝本
在大型应用中经常会使用蓝本,在蓝本视图中集成CKEditor的步骤和app视图基本相同。

1. 创建蓝本时需指明蓝本static目录的绝对路径

demo = Blueprint('demo', static_folder="/path/to/static")

2. 对应url需加上蓝本端点

<script src="{{url_for('.static', filename='ckeditor/ckeditor.js')}}"></script>

<script type="text/javascript">
  CKEDITOR.replace(
    "ckeditor_demo", {
      filebrowserUploadUrl: './ckupload/'
    }
  );
</script>

3. 设置endpoint端点值

response = form.upload(endpoint=demo)
Python 相关文章推荐
详解python中的json和字典dict
Jun 22 Python
Python基于SMTP协议实现发送邮件功能详解
Aug 14 Python
python梯度下降法的简单示例
Aug 31 Python
Python集中化管理平台Ansible介绍与YAML简介
Jun 12 Python
浅谈Python中函数的定义及其调用方法
Jul 19 Python
关于django 1.10 CSRF验证失败的解决方法
Aug 31 Python
python队列原理及实现方法示例
Nov 27 Python
Python中import导入不同目录的模块方法详解
Feb 18 Python
python实现TCP文件传输
Mar 20 Python
python怎么调用自己的函数
Jul 01 Python
Python通过yagmail实现发送邮件代码解析
Oct 27 Python
总结Python常用的魔法方法
May 25 Python
Linux中安装Python的交互式解释器IPython的教程
Jun 13 #Python
浅谈python中的面向对象和类的基本语法
Jun 13 #Python
深入理解python多进程编程
Jun 12 #Python
python中根据字符串调用函数的实现方法
Jun 12 #Python
python中函数总结之装饰器闭包详解
Jun 12 #Python
Python备份目录及目录下的全部内容的实现方法
Jun 12 #Python
深入理解python中的闭包和装饰器
Jun 12 #Python
You might like
php使用ICQ网关发送手机短信
2013/10/30 PHP
Laravel 读取 config 下的数据方法
2019/10/13 PHP
PHP配合fiddler抓包抓取微信指数小程序数据的实现方法分析
2020/01/02 PHP
xheditor与validate插件冲突的解决方案
2010/04/15 Javascript
javascript之AJAX框架使用说明
2010/04/24 Javascript
jquery实现用户打分评分特效
2015/05/28 Javascript
js实现黑色简易的滑动门网页tab选项卡效果
2015/08/31 Javascript
vue-router命名视图的使用讲解
2019/01/19 Javascript
JS图片预加载三种实现方法解析
2020/05/08 Javascript
Python下的Mysql模块MySQLdb安装详解
2014/04/09 Python
Python使用base64模块进行二进制数据编码详解
2018/01/11 Python
全面分析Python的优点和缺点
2018/02/07 Python
Python的条件表达式和lambda表达式实例
2019/01/31 Python
python3.6生成器yield用法实例分析
2019/08/23 Python
python 进程 进程池 进程间通信实现解析
2019/08/23 Python
python多线程同步之文件读写控制
2021/02/25 Python
Python 多线程,threading模块,创建子线程的两种方式示例
2019/09/29 Python
python编写计算器功能
2019/10/25 Python
numpy数组做图片拼接的实现(concatenate、vstack、hstack)
2019/11/08 Python
python实现低通滤波器代码
2020/02/26 Python
利用Python将图片中扭曲矩形的复原
2020/09/07 Python
详解python polyscope库的安装和例程
2020/11/13 Python
html5 分层屏幕适配的方法
2018/03/16 HTML / CSS
德国柯吉澳趣味家居:Koziol
2017/08/24 全球购物
宠物店的创业计划书范文
2014/01/11 职场文书
大学生自助营养快餐店创业计划书
2014/01/13 职场文书
工作迟到检讨书
2014/02/21 职场文书
互联网电子商务专业毕业生求职信
2014/03/18 职场文书
推荐信怎么写
2014/05/09 职场文书
假面舞会策划方案
2014/05/29 职场文书
企业宣传策划方案
2014/05/29 职场文书
个人整改措施落实情况汇报
2014/10/29 职场文书
中国合伙人观后感
2015/06/02 职场文书
电影圆明园观后感
2015/06/03 职场文书
oracle连接ODBC sqlserver数据源的详细步骤
2021/07/25 Oracle
Docker官方工具docker-registry案例演示
2022/04/13 Servers