Use Flask-CKEditor in Flask project integrated rich text editor

Basic Usage

installation

The first to use tools such as pip or Pipenv install or update:

$ pip install -U flask-ckeditor

Initialization extension

Under normal circumstances, you only need to import and instantiate CKEditor class and pass to program example:

from flask_ckeditor import CKEditor

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

If you use a factory function, you can also call init_app () method to initialize:

from flask_ckeditor import CKEditor

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

The introduction of CKEditor resources

In order to use CKEditor, we first introduced the CKEditor JavaScript files and other resources in the template. The recommended practice is to write your own resource references statement, you can provide in CKEditor Online Builder to build a custom package of resources, under static catalog download, unzip into the project, and the introduction of ckeditor.js file in the resource bundle, such as ( The actual path adjust as needed):

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

If you do not need to customize, it can also be loaded from the CDN:

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

Finally, as an alternative option, you can also use Flask-CKEditor provided ckeditor.load () method to generate a reference statement:

{{ ckeditor.load() }}

It defaults to load resources from CDN, the configuration variable is set to True CKEDITOR_SERVE_LOCAL will use the extended built-in local resources. In addition, you can also use custom_url parameters to use a custom resource bundles:

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

Create a text area CKEditor

Flask-CKEditor CKEditor offers two ways to text area:

1. Integration with WTForms / Flask-WTF

Flask-CKEditor CKEditorField provides a class field, and you usually introduced from WTForms StringField, SubmitField same usage. In fact, it is to TextAreaField WTForms provided by the packaging.

As an example, we can create a form class to write articles. This form class contains a header field (StringField), a text field (CKEditorField) and a submit field (SubmitField). You will see where the body field used 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')

In the template rendering text editing 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') }}

The only caveat is that we need to call ckeditor.config () method after the resource statement to make reference to CKEditor configuration and initialization, and the value of the name parameter is set to the attribute name CKEditor fields, here namely body.

When the form is submitted, you can get to the same data through form.attr.data property like other fields, text areas where the data that is form.body.data.

2. manually create

If you do not use WTForms / Flask-WTF, you can directly use ckeditor.create Flask-CKEditor provided () method to create text editing area in the template:

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

{{ ckeditor.load() }}
{{ ckeditor.config() }}  <!-- 这时不用设置name参数 -->

After the form is submitted, you can use the keys acquired as ckeditor corresponding values ​​from the form data, i.e. request.form.get ( 'ckeditor').

Example text area

Configuration Variables

Flask-CKEditor provides these configuration variables (see text form here ):

Flask-CKEditor supported configuration

upload picture

When using a text editor to write articles, upload pictures is a very common requirement. In CKEditor, the pictures can be uploaded via File Browser achieve plug-ins. Flask program in the server side, you need to do three things:

  1. Create a view function to process and save the file to upload
  2. Create a view function to get a picture file, similar to the built-in static endpoint Flask
  3. The configuration variable CKEDITOR_FILE_UPLOADER set to the URL or endpoints view function

The 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') # 获取上传图片文件对象 # Add more validations here extension = f.filename.split('.')[1].lower() if extension not in ['jpg', 'gif', 'png', 'jpeg']: # 验证文件类型示例 return upload_fail(message='Image only!') # 返回upload_fail调用 f.save(os.path.join('/the/uploaded/directory', f.filename)) url = url_for('uploaded_files', filename=f.filename) return upload_success(url=url) # 返回upload_success调用
Note Incoming request.files.get () key must be 'upload', which is the value of CKEditor upload field name defined.

In the process of uploading files view function, you must return upload_success () calls, per the url parameter to get the uploaded file URL. Under normal circumstances, in addition to save the file, you need to upload pictures validation and processing (size, format, file name processing, etc., specific access to this "Flask file upload (a): Native to achieve" understanding), in when the verification fails, you need to return upload_fail () calls, and use the message parameters passed in the error message.

When set CKEDITOR_FILE_UPLOADER configuration variables, you can open the Picture button to open the pop-see uploads a new label point in the editing area. In addition, you can also drag and drop images directly into the editing area to upload a file, or copy and paste it into a text file upload area (CKEditor> = 4.5).

Picture upload example

Tip corresponding sample program in examples / image-upload / directory.

If CKEditor version you are using is less than 4.5, use the following ways:

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.uploader def 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 

Picture upload request to add CSRF protection

If you want to upload pictures of requests to add CSRF protection can be achieved by CSRFProtect (Flask-WTF built), first install Flask-WTF:

$ pip install flask-wtf

Then initialize extension:

from flask_wtf import CSRFProtect

csrf = CSRFProtect(app) 

Flask-CKEditor 0.4.3 version built-in support for CSRFProtect when using CSRFProtect, just need to set the configuration variable `CKEDITOR_ENABLE_CSRF`` True` to open CSRF protection:

app.config['CKEDITOR_ENABLE_CSRF'] = True

By the way, inside the Flask-CKEditor need to upload pictures CSRF tokens into the AJAX request header, this newly added by CKEditor version 4.9.0 a configuration option  fileTools_requestHeaders  realize, this configuration can be used to want to insert the file upload request from defined header fields. So, if you want to achieve CSRF protection, CKEditor version 4.9.0 or greater required.

Code syntax highlighting

Code syntax highlighting by Code Snippet achieved (based hightlight.js) plug-in, you can configure the variables CKEDITOR_ENABLE_CODESNIPPET Ture set to open. Prior to this, you need to make sure to install this plugin (built-in resource pack contains this plugin).

In order to correctly render the block of code, you also need to introduce a corresponding resource file, the easiest way is to use Flask-CKEditor provided ckeditor.load_code_theme () method:

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

You can set the theme CKEDITOR_CODE_THEME syntax highlighting through configuration variables, the default is monokai_sublime, you can at this page to see all the available strings corresponding theme.

Syntax highlighting examples

Use the sample program

Warehouse project provides five sample program, displaying basic usage, image upload insert the code syntax highlighting, Markdown mode and does not use Flask-WTF / WTForms. Basic sample program, for example, you can get it and run the following command:

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

And then access the browser .

Guess you like

Origin www.cnblogs.com/easy-test/p/12500300.html