Tutorial on integrating CKEditor Rich text editor in Python's flask framework

Source: Internet
Author: User
CKEditor is one of the best visible Web editor available today, and it is written in JavaScript. Features powerful, easy to configure, cross-browser, support a variety of programming languages, open source and so on. It is very popular, the Internet is easy to find relevant technical documents, many domestic Web projects and large sites have adopted ckeditor.

Download CKEditor
Visit the official website of CKEditor, go to the download page, select Standard package (usually enough for the function), then click the Download CKEditor button to download the installation file in zip format. If you want to try more features, you can choose to download the full package.

After downloading the CKEditor, unzip to the Flask Project Static/ckeditor directory.

Using CKEditor in Flask projects
Using CKEditor in a flask project requires only two steps:

In

Because the ckeditor is good enough, the second step can only be appended with the class attribute value named CKEditor, and CKEditor will automatically replace it. such as:</p>

      A Simple Page with CKEditor    
 
                

The CKEditor script file can also refer to the files on the CDN, and here are a few reference links:

Basic Edition (mini version)

Standard Edition

Full version
Enable upload function
The default configuration, CKEditor is not enabled upload function, to turn on the upload function, but also quite simple, just need to modify the configuration simple. Here's a look at a couple of related configuration values:

    • Filebrowseruploadurl: File upload path. If set, the Upload button will appear in the links, Pictures, Flash dialog window.
    • 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, whose value is set to/ckupload/(this URL is defined later in flask).

There are 2 main ways to set configuration values:

Method 1: set by ckeditor the configuration file config.js of the root directory:

Ckeditor.editorconfig = function (config) {  //...  File Upload url  config.filebrowseruploadurl = '/ckupload/';  // ...};

Method 2: put the setting value into Ckeditor.replace () as a parameter:

flask Processing upload requests
ckeditor upload function is a unified interface, that is, an interface can handle image upload, file upload, flash upload. Let's take a look at the code:

Def gen_rnd_filename (): Filename_prefix = Datetime.datetime.now (). Strftime ('%y%m%d%h%m%s ') return '%s%s '% (filename_ Prefix, str (random.randrange (10000))) @app. Route ('/ckupload/', methods=[' POST ') def ckupload (): "" "CKEditor File Upload "" error = ' url = ' callback = Request.args.get ("Ckeditorfuncnum") if Request.method = = ' POST ' and ' UPL Oad ' in request.files:fileobj = request.files[' upload '] fname, fext = Os.path.splitext (fileobj.filename) Rnd_nam E = '%s%s '% (Gen_rnd_filename (), fext) filepath = Os.path.join (app.static_folder, ' upload ', rnd_name) # Check if the path exists, does not exist      In the then create 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 ', fi Lename= '%s/%s '% (' upload ', rnd_name)) Else:error = ' Post error ' res = ' """% (callback, URL, error) Response = Make_response (res) response.headers[" content-type "] =" text/html "return respons E

Upload file Capture and save section is relatively simple, is the standard file upload. Here is the main talk about how to callback after the successful upload problem.

After the CKEditor file is uploaded, the server returns the HTML file, the HTML file contains the JavaScript script, the JS script invokes a callback function, and if there is no error, the callback function transfers the returned URL to the CKEditor processing.

These 3 parameters are sequentially:

    • Ckeditorfuncnum: callback function ordinal. CKEditor submitted to the server via URL parameters
    • URL: The URL of the file after uploading
    • ERR: Error message. Returns an empty string if there is no error

Use Blueprint
The blueprint is often used in large-scale applications, and the steps to integrate CKEditor in the Blueprint view are essentially the same as the app view.

1. Specify the absolute path of the blueprint static directory when creating a blueprint

Demo = Blueprint (' demo ', static_folder= "/path/to/static")

2. The corresponding URL must be a blueprint endpoint

3. Set the endpoint endpoint value

Response = Form.upload (Endpoint=demo)
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.