写网站时我们经常会使用到富文本编辑器,flask中使用ckeitor也是非常的简单。
第一步,官网下载ckeditor:https://ckeditor.com/ckeditor-4/download/
有几个版本可供选择,我选择的是完整版。
第二步,解压,将其解压至flask中statics下的ckeditor目录下,解压后如下图:
第三步,在相应的html中导入ckeditor.js:
第四步,在html中需要配置富文本编辑器的地方创建如下的textarea标签:
<textarea name ="editor1" id="editor1" rows="10" cols="80"></textarea>
第五步,在html中添加script脚本:
其中filebrowserUploadUrl是ckeditor中的文件上传路径,需要创建/upload/路由。
第六步,创建/upload/路由:
import os
import datetime
import random
from flask import render_template,request,url_for,make_response
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('/upload/', methods=['POST', 'OPTIONS'])
def upload():
"""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
如果需要语法高亮,只需要下载codesnippet:https://ckeditor.com/cke4/addon/codesnippet
将其解压至ckeditor目录下的plugins下:
然后再html中script中加入如下代码:
再回到页面中就会出现下面的图标:
这样就完成了flask中ckeditor的配置,可以愉快的写文章了。