Home > Article > Backend Development > CKeditor rich text editor integrated into Python's Flask framework
CKeditor is one of the best visible and available web page editors, written in JavaScript. It has the characteristics of powerful functions, easy configuration, cross-browser, support for multiple programming languages, and open source. It is very popular, and it is easy to find relevant technical documents on the Internet. Many domestic WEB projects and large websites use CKeditor.
Download CKeditor
Visit the CKeditor official website, enter the download page, select Standard Package (generally the functions are sufficient), and then click the Download CKEditor button to download the ZIP format installation files. If you want to try more features, you can choose to download the Full Package.
After downloading CKeditor, unzip it to the static/ckeditor directory of the Flask project.
Using CKeditor in Flask project
To use CKeditor in Flask project, you only need to perform two steps:
Introduce CKeditor in the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag Main script file. You can import local files or reference files on CDN.
Use CKEDITOR.replace() to replace the existing 4750256ae76b6b9d804861d8f69e79d3 tag with CKEditor.
Sample code:
<!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>
Because CKeditor is good enough, the second step can also only add a class attribute value named ckeditor to 4750256ae76b6b9d804861d8f69e79d3 , CKeditor will automatically replace it. For example:
<!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 script files can also reference files on CDN. Here are several reference links:
<script src="//cdn.ckeditor.com/4.4.6/basic/ckeditor.js"></script>
Basic version (mini version)
<script src="//cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>
Standard version
<script src="//cdn.ckeditor.com/4.4.6/full/ckeditor.js"></script>
Full version
Enable upload function
Under the default configuration, CKEditor does not enable the upload function. To enable the upload function, it is quite simple. Just simply modify the configuration. Let’s take a look at several related configuration values:
filebrowserUploadUrl: file upload path. If set, the upload button will appear in the link, image, and Flash dialog windows.
filebrowserImageUploadUrl: Image upload path. If not set, the filebrowserUploadUrl value is used.
filebrowserFlashUploadUrl: Flash upload path. If not set, the filebrowserUploadUrl value is used.
For convenience, here we only set the filebrowserUploadUrl value, and its value is set to /ckupload/ (this URL will be defined in Flask later).
There are two main methods for setting configuration values:
Method 1: Set through the configuration file config.js in the root directory of CKEditor:
CKEDITOR.editorConfig = function( config ) { // ... // file upload url config.filebrowserUploadUrl = '/ckupload/'; // ... };
Method 2: Put the setting value as a parameter into CKEDITOR.replace():
<script> CKEDITOR.replace('editor1', { filebrowserUploadUrl: '/ckupload/', }); </script>
Flask handles upload requests
CKEditor upload function is a unified interface, that is, one interface can handle image upload, file upload, and Flash upload. Let’s take a look at the code first:
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
The acquisition and saving part of the uploaded file is relatively simple and is a standard file upload. Here we mainly talk about how to call back after the upload is successful.
After the CKEditor file is uploaded, the server returns an HTML file. The HTML file contains a JAVASCRIPT script. The JS script will call a callback function. If there is no error, the callback function will transfer the returned URL to CKEditor for processing.
These three parameters are:
CKEditorFuncNum: callback function serial number. CKEditor submits it to the server through URL parameters
URL: URL of the uploaded file
Error: Error message. If there is no error, return an empty string
Use blueprints
Blueprints are often used in large applications, and the steps and apps of CKEditor are integrated in the blueprint view. The views are basically the same.
1. When creating a blueprint, you need to specify the absolute path of the blueprint's static directory
demo = Blueprint('demo', static_folder="/path/to/static")
2. The corresponding url needs to add the blueprint endpoint
<script src="{{url_for('.static', filename='ckeditor/ckeditor.js')}}"></script> <script type="text/javascript"> CKEDITOR.replace( "ckeditor_demo", { filebrowserUploadUrl: './ckupload/' } ); </script>
3. Set the endpoint endpoint value
response = form.upload(endpoint=demo)
More Python's Flask framework For articles related to the integrated CKeditor rich text editor, please pay attention to the PHP Chinese website!