Home  >  Article  >  Backend Development  >  CKeditor rich text editor integrated into Python's Flask framework

CKeditor rich text editor integrated into Python's Flask framework

高洛峰
高洛峰Original
2017-03-03 13:39:151819browse

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(&#39;static&#39;, filename=&#39;ckeditor/ckeditor.js&#39;) }}"></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(&#39;editor1&#39;);
      </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(&#39;static&#39;, filename=&#39;ckeditor/ckeditor.js&#39;) }}"></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 = &#39;/ckupload/&#39;;
  // ...
};

Method 2: Put the setting value as a parameter into CKEDITOR.replace():

<script>
CKEDITOR.replace(&#39;editor1&#39;, {
  filebrowserUploadUrl: &#39;/ckupload/&#39;,
});
</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(&#39;%Y%m%d%H%M%S&#39;)
  return &#39;%s%s&#39; % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route(&#39;/ckupload/&#39;, methods=[&#39;POST&#39;])
def ckupload():
  """CKEditor file upload"""
  error = &#39;&#39;
  url = &#39;&#39;
  callback = request.args.get("CKEditorFuncNum")
  if request.method == &#39;POST&#39; and &#39;upload&#39; in request.files:
    fileobj = request.files[&#39;upload&#39;]
    fname, fext = os.path.splitext(fileobj.filename)
    rnd_name = &#39;%s%s&#39; % (gen_rnd_filename(), fext)
    filepath = os.path.join(app.static_folder, &#39;upload&#39;, rnd_name)
    # 检查路径是否存在,不存在则创建
    dirname = os.path.dirname(filepath)
    if not os.path.exists(dirname):
      try:
        os.makedirs(dirname)
      except:
        error = &#39;ERROR_CREATE_DIR&#39;
    elif not os.access(dirname, os.W_OK):
      error = &#39;ERROR_DIR_NOT_WRITEABLE&#39;
    if not error:
      fileobj.save(filepath)
      url = url_for(&#39;static&#39;, filename=&#39;%s/%s&#39; % (&#39;upload&#39;, rnd_name))
  else:
    error = &#39;post error&#39;
  res = """

<script type="text/javascript">
 window.parent.CKEDITOR.tools.callFunction(%s, &#39;%s&#39;, &#39;%s&#39;);
</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(&#39;demo&#39;, static_folder="/path/to/static")

2. The corresponding url needs to add the blueprint endpoint

<script src="{{url_for(&#39;.static&#39;, filename=&#39;ckeditor/ckeditor.js&#39;)}}"></script>

<script type="text/javascript">
  CKEDITOR.replace(
    "ckeditor_demo", {
      filebrowserUploadUrl: &#39;./ckupload/&#39;
    }
  );
</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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn