flask-ckeditor documentation

31
Flask-CKEditor Documentation Release 0.2.0 Grey Li Apr 25, 2021

Upload: others

Post on 16-Oct-2021

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Flask-CKEditor Documentation

Flask-CKEditor DocumentationRelease 0.2.0

Grey Li

Apr 25, 2021

Page 2: Flask-CKEditor Documentation
Page 3: Flask-CKEditor Documentation

Contents

1 Contents 31.1 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 Advanced Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.4 FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.5 Try Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 API Reference 132.1 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3 Changelog 153.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4 Development 19

5 Authors 21

6 License 23

Python Module Index 25

Index 27

i

Page 4: Flask-CKEditor Documentation

ii

Page 5: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

CKEditor integration for Flask, add support to image upload, code syntax highlighting and more.

Contents 1

Page 6: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

2 Contents

Page 7: Flask-CKEditor Documentation

CHAPTER 1

Contents

1.1 Basic Usage

1.1.1 Installation

$ pip install flask-ckeditor

1.1.2 Initialization

This extension needs to be initialized in the usual way before it can be used:

from flask_ckeditor import CKEditor

app = Flask(__name__)ckeditor = CKEditor(app)

This extension also supports the Flask application factory pattern by allowing you to create a CKEditor object andthen separately initialize it for an app:

from flask_ckeditor import CKEditor

ckeditor = CKEditor()

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

3

Page 8: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

1.1.3 Include CKEditor Resources

In the template in which you want to put a CKEditor textarea, call ckeditor.load() in <head></head> orbefore </body>:

<body>...{{ ckeditor.load() }}

</body>

By default, it will load the CKEditor resources from CND (cdn.ckeditor.com), you can setCKEDITOR_SERVE_LOCAL to True to use built-in resources. You can use custom_url to load your cus-tom CKEditor build:

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

CKEditor provides five types of preset (see comparison table for the differences):

• basic

• standard default value

• full

• standard-all (only available from CDN)

• full-all (only available from CDN)

You can use pkg_type parameter or CKEDITOR_PKG_TYPE configuration variable to set the package type. Forexample:

{{ ckeditor.load(pkg_type="basic") }}

Or:

app = Flask(__name__)app.config['CKEDITOR_PKG_TYPE'] = 'basic'ckeditor = CKEditor(app)

This method is just a helper to generate <script> to include CKEditor resources, you can also write <script>element directly:

<script src="https://cdn.ckeditor.com/4.10.0/standard/ckeditor.js"></script>

1.1.4 Create a CKEditor Textarea

It’s quite simple, just call ckeditor.create() in the template:

<form method="post">{{ ckeditor.create() }}<input type="submit">

</form>

You can use value parameter to pass preset value (i.e. ckeditor.create(value='blah...blah...').

4 Chapter 1. Contents

Page 9: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

1.1.5 Get the Data

Since the CKEditor textarea is just a normal <textarea> element, you can get the data from request.form bypassing ckeditor as key:

from flask import request, render_template

@app.route('/write')def new_post():

if request.method == 'POST':data = request.form.get('ckeditor') # <--

return render_template('index.html')

1.1.6 Working with Flask-WTF/WTForms

When using Flask-WTF/WTForms, you can import the CKEditorField provided by Flask-CKEditor and use itjust like StringField:

from flask_wtf import FlaskFormfrom flask_ckeditor import CKEditorFieldfrom wtforms import StringField, SubmitField

class PostForm(FlaskForm):title = StringField('Title')body = CKEditorField('Body') # <--submit = SubmitField('Submit')

One more step is to call ckeditor.config() and pass the CKEditorField attribute’s name:

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

</form>

{{ ckeditor.load() }}{{ ckeditor.config(name='body') }}</body>

In the view function, you can get the data either by request.form.get('body') or form.body.data.

Tip: Check the demo application at examples/basic and examples/without-flask-wtf.

1.1.7 Preset Value in CKEditor Textarea

When you implement an edit feature for your CMS, you will need to get the article data from database, then preset thevalue into the CKEditor textarea. First you need to pass the value into template:

@app.route('/edit')def edit_post():

article_body = get_the_article_body_from_somewhere()return render_template('edit.html', article_body=article_body)

1.1. Basic Usage 5

Page 10: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

Then pass it to CKEditor with value parameter:

<form method="post">{{ ckeditor.create(value=article_body) }}<input type="submit">

</form>

If you are using Flask-WTF/WTForms, it’s even more simple, just pass the value to the form field’s data attribute:

@app.route('/edit')def edit_post():

form = EditForm()form.body.data = get_the_article_body_from_somewhere() # <--return render_template('edit.html', form=form)

1.2 Configuration

1.2.1 Register Configuration

Except for CKEDITOR_SERVE_LOCAL and CKEDITOR_PKG_TYPE, when you use other configuration variables,you have to call ckeditor.config() in the template to make them register with CKEditor:

<body>... <!-- {{ ckeditor.load() }} or <script src="/path/to/ckeditor.js"> -->{{ ckeditor.config() }}

</body>

When using Flask-WTF/WTForms, you have to pass the field name as name in ckeditor.config(), for example:

<body>... <!-- {{ ckeditor.load() }} or <script src="/path/to/ckeditor.js"> --

→˓>{{ ckeditor.config(name='description') }}

</body>

When using Flask-Admin, the name value will be the field name you overwritten with form_overrides =dict(the_field_name=CKEditorField). For example:

{% extends 'admin/model/edit.html' %}

{% block tail %}{{ super() }}

... <!-- {{ ckeditor.load() }} or <script src="/path/to/ckeditor.js"> -->{{ ckeditor.config(name='the_field_name') }}

{% endblock %}

If you create the CKEditor through ckeditor.create(), the default value (name='ckeditor') will be used.

1.2.2 Available Configuration

The configuration options available are listed below:

6 Chapter 1. Contents

Page 11: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

Name DefaultValue

Info

CKEDI-TOR_SERVE_LOCAL

False Flag used to enable serving resources from local when use ckeditor.load(), default is to retrieve from CDN.

CKEDI-TOR_PKG_TYPE

'standard'The package type of CKEditor, one of basic, standard, full,standard-all and full-all. The last two options only availablefrom CDN.

CKEDI-TOR_LANGUAGE

None The lang code string to set UI language in ISO 639 format, for example:zh, en, jp etc. Leave it unset to enable auto detection by user’s browsersetting.

CKEDI-TOR_HEIGHT

CKEditordefault

The height of CKEditor textarea, in pixel.

CKEDI-TOR_WIDTH

CKEditordefault

The width of CKEditor textarea, in pixel.

CKEDI-TOR_FILE_UPLOADER

None The URL or endpoint that handles file upload.

CKEDI-TOR_FILE_BROWSER

None The URL or endpoint that handles file browser.

CKEDI-TOR_ENABLE_CODESNIPPET

False Flag used to enable codesnippet plugin, the plugin must be installed (in-cluded in built-in resources).

CKEDI-TOR_CODE_THEME

'monokai_sublime'Set code snippet highlight theme when codesnippet plugin was enabled.

CKEDI-TOR_EXTRA_PLUGINS

[] A list of extra plugins used in CKEditor, the plugins must be installed.

CKEDI-TOR_ENABLE_CSRF

False Flag used to enable CSRF protection for image uploading, see AdvancedUsage for more details.

CKEDI-TOR_UPLOAD_ERROR_MESSAGE

'Uploadfailed.'

Default error message for failed upload.

1.2.3 Custom Configuration String

In addition, you can pass custom settings with custom_config argument:

{{ ckeditor.config(custom_config="uiColor: '#9AB8F3'") }}

Keep it mind that the proper syntax for each option is configuration name : configuration value.You can use comma to separate multiple key-value pairs. See the list of available configuration settings on CKEditordocumentation.

If you are using Flask-WTF/WTForms or Flask-Admin, remember to pass the form field name with name:

<body>... <!-- {{ ckeditor.load() }} or <script src="/path/to/ckeditor.js"> --

→˓>{{ ckeditor.config(name='description') }} <!-- use name='text' for

→˓Flask-Admin --></body>

1.2.4 Configuring Multiple Text Area

If you need to create multiple text areas in one page, here are some tips:

1.2. Configuration 7

Page 12: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

Without Flask-WTF/WTForms

Create two text areas with different name and configure them with a unique name:

<h1>About me</h1>{{ ckeditor.create(name='bio') }}

<h1>About my team</h1>{{ ckeditor.create(name='team') }}

{{ ckeditor.load() }}

{{ ckeditor.config(name='bio') }}{{ ckeditor.config(name='team') }}

With Flask-WTF/WTForms

When creating multiple forms with Flask-WTF/WTForms, you just need to create multiple CKEditorField fields:

from flask_wtf import FlaskFormfrom flask_ckeditor import CKEditorFieldfrom wtforms import StringField, SubmitField

class PostForm(FlaskForm):title = StringField('Title')bio = CKEditorField('About me') # <--team = CKEditorField('About my team') # <--submit = SubmitField('Submit')

In the template, you render them and configure them with the right name:

{{ form.bio() }}{{ form.team() }}{{ form.submit() }}

{{ ckeditor.load() }}

{{ ckeditor.config(name='bio') }}{{ ckeditor.config(name='team') }}

1.2.5 Overwriting Global Configurations

Sometimes you may want to use a different configuration for multiple text areas, in this case, you can pass the specifickeyword arguments into ckeditor.config() directly.

The keyword arguments should map the corresponding configuration variables in this way:

• CKEDITOR_LANGUAGE –> language

• CKEDITOR_WIDTH –> width

• CKEDITOR_FILE_UPLOADER –> file_uploader

• etc

example:

8 Chapter 1. Contents

Page 13: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

{{ ckeditor.config(lanuage='en', width=500) }}

In the end, the keyword argument you pass will overwrite the corresponding configurations.

Comparatively, you can use serve_local and pkg_type in ckeditor.load() to overwriteCKEDITOR_SERVE_LOCAL and CKEDITOR_PKG_TYPE.

1.3 Advanced Usage

1.3.1 Image Upload

CKEditor >= 4.5

The built-in CKEditor package includes a File Browser plugin. With this plugin, you can upload and insert im-ages with the image widget. You need to set CKEDITOR_FILE_UPLOADER to the URL or endpoint which han-dles uploading files, and the upload view must return upload_success() call with the url of the uploadedimage. Usually, you also need to validate the uploaded image, then you can use upload_fail() to returnan error message with the message argument. If message was None, the value in the configuration variableCKEDITOR_UPLOAD_ERROR_MESSAGE will be used, defaults to Upload failed.. Here is the full example:

from flask_ckeditor import upload_success, upload_fail

app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # this value can be endpoint or url

@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')# Add more validations hereextension = f.filename.split('.')[-1].lower()if extension not in ['jpg', 'gif', 'png', 'jpeg']:

return upload_fail(message='Image only!')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 call

Note: The key passed to request.files.get() must be 'upload',

it’s defined by CKEditor and it’s not the name of the view function.

In the template, you have to call ckeditor.config() to make the configuration work:

{{ ckeditor.config() }}

Tip: When using Flask-WTF/WTForms, you have to pass the field name as name in ckeditor.config(),for example ckeditor.config(name='description'). If you create the CKEditor through ckeditor.create(), the default value (ckeditor) will be used.

1.3. Advanced Usage 9

Page 14: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

Now you will find the Upload tab appear in the image widget. Besides, you can drag and drop the image directlyinto the editor area or copy and paste the image (CKEditor >= 4.5).

Tip: Check the demo application at examples/image-upload/.

CKEditor < 4.5

If the CKEditor version you use is below 4.5, you will need to use @ckeditor.uploader to decorate the viewfunction that handles the file upload. The upload view must return the url of the uploaded image. For example:

from flask import send_from_directory

app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # this value can be endpoint or url

@app.route('/files/<filename>')def uploaded_files(filename):

path = '/the/uploaded/directory'return send_from_directory(path, filename)

@app.route('/upload', methods=['POST'])@ckeditor.uploaderdef upload():

f = request.files.get('upload')f.save(os.path.join('/the/uploaded/directory', f.filename))url = url_for('uploaded_files', filename=f.filename)return url

You can use the configuration variable CKEDITOR_UPLOAD_ERROR_MESSAGE to customize the error messagewhen the upload failed, it defaults to Upload failed.

Note: The key passed to request.files.get() must be 'upload',

it’s defined by CKEditor and it’s not the name of the view function.

In the template, you have to call ckeditor.config() to make the configuration work:

{{ ckeditor.config() }}

Tip: When using Flask-WTF/WTForms, you have to pass the field name as name in ckeditor.config(),for example ckeditor.config(name='description'). If you create the CKEditor through ckeditor.create(), the default value (ckeditor) will be used.

Now you will find the Upload tab appear in the image widget.

1.3.2 CSRF Protection for Image Upload

Required version: CKEditor >= 4.9.0

The CSRF Protection feature was provided by Flask-WTF’s CSRFProtect extension, so you have to install Flask-WTF first:

10 Chapter 1. Contents

Page 15: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

$ pip install flask-wtf

Then initialize the CSRFProtect extension:

from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)

# the secret key used to generate CSRF tokenapp.config['SECRET_KEY'] = 'dev key'

# enable CSRF protectionapp.config['CKEDITOR_ENABLE_CSRF'] = True

csrf = CSRFProtect(app)

Make sure to set the secret key and set CKEDITOR_ENABLE_CSRF to True. Now all the image upload requests willbe protected!

1.3.3 Code Snippet Highlight

The built-in CKEditor package includes a Code Snippet plugin. You need to setCKEDITOR_ENABLE_CODESNIPPET to True to enable it. You can set the code theme through the config-uration option CKEDITOR_CODE_THEME. The default theme is monokai_sublime. See all available themes andthe list of valid theme strings on this page.

Another step is to load code theme resources on the page you want to display the text in:

<head>...{{ ckeditor.load_code_theme() }}

</head>

Check the demo application at examples/codesnippet/.

1.4 FAQ

1.4.1 How to make this extension work with Flask-Admin?

Ckeck this SO answer and the demo application at examples/flask-admin.

1.5 Try Examples

Open a terminal, type the commands below one by one:

$ git clone https://github.com/greyli/flask-ckeditor$ cd flask-ckeditor/examples$ pip install -r requirements.txt$ python basic/app.py

1.4. FAQ 11

Page 16: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

Then go to http://127.0.0.1:5000 with your favourite browser.

Aside from the basic example, there are five additional examples:

• examples/codesnippet: This example demonstrates how to use the Code Snippet plugin.

• examples/flask-admin: This example demonstrates how to use CKEditor for Flask-Admin.

• examples/flask-admin-upload: This example demonstrates how to use CKEditor for Flask-Admin with imageupload.

• examples/image-upload: This example demonstrates how to support image upload in Flaks-CKEditor.

• examples/without-flask-wtf: This example demonstrates how to use CKEditor without Flask-WTF.

12 Chapter 1. Contents

Page 17: Flask-CKEditor Documentation

CHAPTER 2

API Reference

If you are looking for information on a specific function, class or method, this part of the documentation is for you.

2.1 API Reference

2.1.1 CKEditor Object in Template

2.1.2 CKEditor Object in Python

2.1.3 Image Upload

2.1.4 Utils

13

Page 18: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

14 Chapter 2. API Reference

Page 19: Flask-CKEditor Documentation

CHAPTER 3

Changelog

3.1 Changelog

3.1.1 0.4.6

Release date: 2021/4/25

• Support to pass standard-all and full-all as CKEditor package type.

3.1.2 0.4.5

Release date: 2021/4/24

• Fix unnecessary “ckeditor” class when using ckeditor.config().

3.1.3 0.4.4.1

Release date: 2020/4/28

• Fix project description.

3.1.4 0.4.4

Release date: 2020/4/19

• Upgrade CKEditor from 4.9.2 to 4.14.0.

• Fix multiple minor bugs.

• Fix documentation.

15

Page 20: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

3.1.5 0.4.3

Release date: 2018/11/8

• Add CSRF protect support for image uplaoding, based on Flask-WTF (CSRFProtect).

3.1.6 0.4.2

Release date: 2018/8/24

• Add documentation.

• Remove built-in support for markdown plugin since it’s unmaintained and not work with CKEditor > 4.6.

• Rename argument codesnippet to enable_codesnippet in ckeditor.config().

• Add serve_local argument for ckeditor.load().

3.1.7 0.4.1

Release date: 2018/6/8

• Change built-in resource’s url path to ckeditor/static/... to prevent conflict with user’s static path.

3.1.8 0.4.0

Release date: 2018/5/29

• Add basic unit test.

• Update resources, fix plugin register bug, use CKEditor 4.9.2.

• Add configuration parameter CKEDITOR_ENABLE_CODESNIPPET, used to enable/disable Code Snippetplugin.

• Added Markdown plugin into built-in resouce, enabled markdown mode viaCKEDITOR_ENABLE_MARKDOWN.

• Added configuration parameter CKEDITOR_EXTRA_PLUGINS, a list used to register extra plugins.

3.1.9 0.3.3

Release date: 2018/2/4

• Added support to set name and value when using ckeditor.create().

3.1.10 0.3.2

Release date: 2018/1/15

• Fixed built-in resources bug.

16 Chapter 3. Changelog

Page 21: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

3.1.11 0.3.1

Release date: 2018/1/13

• The value of CKEDITOR_FILE_UPLOADER, CKEDITOR_FILE_BROWSER, file_uploader andfile_browser in ckeditor.config() can be URL or endpoint.

• Change CKEDITOR_FILE_UPLOAD_URL to CKEDITOR_FILE_UPLOADER.

• Change CKEDITOR_FILE_BROWSER_URL to CKEDITOR_FILE_BROWSER.

• Change ckeditor.config(file_upload_url) to ckeditor.config(file_uploader).

• Change ckeditor.config(file_browser_url) to ckeditor.config(file_browser).

3.1.12 0.3

Release date: 2017/12/4

• Set custom resource url with custom_url argument in load().

• Added support for configuration, config() method used to load config.

• Added support to upload image.

• Added local resources, it can be enabled with CKEDITOR_SERVE_LOCAL, default to False.

3.1.13 0.2

Release date: 2017/9/29

• Added example and basic documentation.

• Added support to custom version and pakage type.

• Import CKEditorField directly from flask_ckeditor.

• Change include_ckeditor() to load().

3.1.14 0.1

Initialize release.

3.1. Changelog 17

Page 22: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

18 Chapter 3. Changelog

Page 23: Flask-CKEditor Documentation

CHAPTER 4

Development

We welcome all kinds of contributions. You can run test like this:

$ python setup.py test

19

Page 24: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

20 Chapter 4. Development

Page 25: Flask-CKEditor Documentation

CHAPTER 5

Authors

Maintainer:

• Grey Li

• Remy Zandwijk

See also the list of contributors who participated in this project.

21

Page 26: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

22 Chapter 5. Authors

Page 27: Flask-CKEditor Documentation

CHAPTER 6

License

This project is licensed under the MIT License (see the LICENSE file for details).

23

Page 28: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

24 Chapter 6. License

Page 29: Flask-CKEditor Documentation

Python Module Index

fflask_ckeditor, 13flask_ckeditor.utils, 13

25

Page 30: Flask-CKEditor Documentation

Flask-CKEditor Documentation, Release 0.2.0

26 Python Module Index

Page 31: Flask-CKEditor Documentation

Index

Fflask_ckeditor (module), 13flask_ckeditor.utils (module), 13

27