Rich text editors are WYSIWYG (What You See Is What You Get) editors (WYSIWYG editors). CKEditor is a popular choice among the open source rich text editors available in Web applications. The flask-Ckeditor extension simplifies the process of integrating CKEditor into Flask projects, allowing you to easily add rich text editors to Flask projects. It contains the following features:

  • Provides WTForms/Flask-WTF integration support
  • Support image upload and insert
  • The Flask configuration is used to set the language, height, and other parameters of the editor
  • Support code block syntax highlighting

Flask Web DevelopmentThe second example program (
Blog program Bluelog) uses this extension.



Basic usage

The installation

Install first using tools such as PIP or Pipenv:

$ pip install flask-ckeditorCopy the code

Initialize the extension

In general, you just need to import and instantiate the CKEditor class and pass in an instance of the program:

from flask_ckeditor import CKEditor

app = Flask(__name__)
ckeditor = CKEditor(app)Copy the code
If you use a factory function, you can also call the init_app() method to initialize it:

from flask_ckeditor import CKEditor

ckeditor = CKEditor()

def create_app():
    app = Flask(__name__)
    ckeditor.init_app(app)
    return appCopy the code

Import the CKEditor resource

To use CKEditor, we first import CKEditor’s JavaScript and other resource files into the template. Ckeditor.js: ckeditor.js: ckeditor.js: ckeditor.js: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor: CKEditor:

<script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></script>Copy the code
If you don’t need to customize it, you can also load it from the CDN:

<script src="/ / cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>Copy the code
Finally, as an alternative, you can also use the ckeditor.load() method provided by flask-ckeditor to generate reference statements:

{{ ckeditor.load() }}Copy the code
It loads resources from the CDN by default, and setting the configuration variable CKEDITOR_SERVE_LOCAL to True uses local resources built into the extension. Alternatively, you can use the custom_URL parameter to use the custom resource bundle:

{{ ckeditor.load(custom_url=url_for('static', filename='ckeditor/ckeditor.js'))}}Copy the code

Create the CKEditor text area

Flask-ckeditor provides two ways to CKEditor text areas:


1. Integration with WTForms/Flask-WTF

Flask-ckeditor provides a CKEditorField class, the same as StringField and SubmitField that you import from WTForms. In fact, it is a wrapper around TextAreaField provided by WTForms.

As an example, we can create a form class for writing articles. The form class contains a title field (StringField), a body field (CKEditorField), and a submission field (SubmitField). You’ll see that the body field uses CKEditorField.

from flask_wtf import FlaskForm
from flask_ckeditor import CKEditorField
from wtforms import StringField, SubmitField

class PostForm(FlaskForm):
    title = StringField('Title')
    body = CKEditorField('Body')
    submit = SubmitField('Submit')Copy the code
In the template rendering the text edit area, we can render the form as usual:

<form method="post">
    {{ form.title.label }}{{ form.title() }}
    {{ form.body.label }}{{ form.body() }}
    {{ form.submit() }}
</form>

{{ ckeditor.load() }}
{{ ckeditor.config(name='body')}}Copy the code
The only thing to note is that we need to call the ckeditor.config() method after the resource reference statement to configure and initialize ckeditor, and set the name parameter to the property name of the Ckeditor field, in this case the body.

When the form is submitted, you can retrieve the data from the form.attr. Data property just like any other field. In this case, the text field data is form.body.data.


2. Create one manually

If you don’t use WTForms/ flask-wtf, then you can create text editing areas in the template directly using the ckeditor.create() method provided by flask-ckeditor:

<form method="post">
    {{ ckeditor.create() }}
    <input type="submit"> </form> {{ ckeditor.load() }} {{ ckeditor.config() }} <! Select * from 'name';Copy the code
After the form is submitted, you can use ckeditor as the key to get the corresponding value from the form data, i.e. Request.form.get (‘ckeditor’).



Prompts complete sample programs in the examples/basic/ and examples/without-flask-wtf directories.

Configuration variables

Flask-ckeditor provides the following configuration variables (see text here) :

Flask-ckeditor configuration supported

Image upload

Uploading images is a common requirement when writing articles with a text editor. In CKEditor, image uploading can be done through the File Browser plug-in. In Flask on the server side, you need to do three things:

  1. Create a view function to process and save the uploaded file
  2. Create a view function to retrieve image files, similar to the static endpoints built into Flask
  3. Set the configuration variable CKEDITOR_FILE_UPLOADER to the URL or endpoint value of this view function
A complete code example is shown below:

from flask_ckeditor import upload_success, upload_fail

app.config['CKEDITOR_FILE_UPLOADER'] = 'upload'

@app.route('/files/<path:filename>')
def uploaded_files(filename):
    path = '/the/uploaded/directory'
    return send_from_directory(path, filename)

@app.route('/upload', methods=['POST'])
def upload():
    f = request.files.get('upload')  Get the uploaded image file object
    # Add more validations here
    if extension not in ['jpg'.'gif'.'png'.'jpeg'] :Verify the file type example
        return upload_fail(message='Image only! ')  # return upload_fail call
    f.save(os.path.join('/the/uploaded/directory', f.filename))
    url = url_for('uploaded_files', filename=f.filename)
    return upload_success(url=url) # return upload_success callCopy the code
Note that the key passed in request.files.get() must be ‘upload’, which is the upload field name value defined by CKEditor.
In the view function that handles the uploaded file, you must return the upload_success() call each time the URL parameter is set to get the URL for the uploaded file. In general, in addition to saving files, you’ll need to validate and manipulate the uploaded images (size, format, file name, etc.). Here’s how to do it: In case validation fails, you need to return the upload_fail() call and pass in an error message using the message argument.

After setting the CKEDITOR_FILE_UPLOADER configuration variable, you can see a new upload label in the pop-up window that opens by clicking the Image button in the edit area. Alternatively, you can drag the image file directly into the edit area for uploading, or copy the file and paste it into the text area for uploading (CKEditor >= 4.5).



The corresponding example program is in the examples/image-upload/ directory.

Code syntax highlights

Code syntax highlighting can be done with a Code Snippet plug-in (based on hightlight.js) that you can turn on by setting the configuration variable CKEDITOR_ENABLE_CODESNIPPET to true. Before you do that, you need to make sure you have the plug-in installed (it’s included in the built-in resource pack).

In order to render the code block correctly, you also need to import the corresponding resource file, the easiest way to do this is to use the CKEditor. Load_code_theme () method provided by flask-ckeditor:

<head>
 ...
 {{ ckeditor.load_code_theme() }}
</head>Copy the code
You can set syntax-highlighted themes by setting the CKEDITOR_CODE_THEME variable, which defaults to monokai_sublime. You can see strings for all available themes on this page.



The example program is in the examples/codesnippet/ directory.

Use sample program

Five sample programs are provided in the project repository, showing basic usage, image upload insertion, code syntax highlighting, Markdown mode, and not using Flask-WTF/WTForms. Take the basic sample program as an example. You can get it and run it with the following command:

$ git clone https://github.com/greyli/flask-ckeditor
$ cd flask-ckeditor/examples
$ pip install -r requirements.txt
$ python basic/app.pyCopy the code
Then go to http://127.0.0.1:5000 in your browser.

In addition, the sample application in the HelloFlask repository under the demos/form directory also contains an example of flask-Dropzone usage.

A link to the

  • GitHub:github.com/greyli/flas…
  • PyPI:pypi.python.org/pypi/Flask-…