Python的Flask框架中集成CKeditor富文本编辑器的教程
CKeditor是目前最优秀的可见即可得网页编辑器之一,它采用JavaScript编写。具备功能强大、配置容易、跨浏览器、支持多种编程语言、开源等特点。它非常流行,互联网上很容易找到相关技术文档,国内许多WEB项目和大型网站均采用了CKeditor。
下载CKeditor
访问CKeditor官方网站,进入下载页面,选择Standard Package(一般情况下功能足够用了),然后点击Download CKEditor按钮下载ZIP格式的安装文件。如果你想尝试更多的功能,可以选择下载Full Package。
下载好CKeditor之后,解压到Flask项目static/ckeditor目录即可。
在Flask项目中使用CKeditor
在Flask项目中使用CKeditor只需要执行两步就可以了:
在<script>标签引入CKeditor主脚本文件。可以引入本地的文件,也可以引用CDN上的文件。<br /> 使用CKEDITOR.replace()把现存的<textarea>标签替换成CKEditor。<br /> 示例代码:</script>
<!DOCTYPE html> <html> <head> <title>A Simple Page with CKEditor</title> <!-- 请确保CKEditor文件路径正确 --> <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></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('editor1'); </script> </form> </body> </html>
因为CKeditor足够优秀,所以第二步也可只为
<!DOCTYPE html> <html> <head> <title>A Simple Page with CKEditor</title> <!-- 请确保CKEditor文件路径正确 --> <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></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脚本文件也可以引用CDN上的文件,下面给出几个参考链接:
<script src="//cdn.ckeditor.com/4.4.6/basic/ckeditor.js"></script>
基础版(迷你版)
<script src="//cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>
标准版
<script src="//cdn.ckeditor.com/4.4.6/full/ckeditor.js"></script>
完整版
开启上传功能
默认配置下,CKEditor是没有开启上传功能的,要开启上传功能,也相当的简单,只需要简单修改配置即可。下面来看看几个相关的配置值:
- filebrowserUploadUrl :文件上传路径。若设置了,则上传按钮会出现在链接、图片、Flash对话窗口。
- filebrowserImageUploadUrl : 图片上传路径。若不设置,则使用filebrowserUploadUrl值。
- filebrowserFlashUploadUrl : Flash上传路径。若不设置,则使用filebrowserUploadUrl值。
为了方便,这里我们只设置filebrowserUploadUrl值,其值设为/ckupload/(后面会在Flask中定义这个URL)。
设置配置值主要使用2种方法:
方法1:通过CKEditor根目录的配置文件config.js来设置:
CKEDITOR.editorConfig = function( config ) { // ... // file upload url config.filebrowserUploadUrl = '/ckupload/'; // ... };
方法2:将设置值放入作为参数放入CKEDITOR.replace():
<script> CKEDITOR.replace('editor1', { filebrowserUploadUrl: '/ckupload/', }); </script>
Flask处理上传请求
CKEditor上传功能是统一的接口,即一个接口可以处理图片上传、文件上传、Flash上传。先来看看代码:
def gen_rnd_filename(): filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S') return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000))) @app.route('/ckupload/', methods=['POST']) def ckupload(): """CKEditor file upload""" error = '' url = '' callback = request.args.get("CKEditorFuncNum") if request.method == 'POST' and 'upload' in request.files: fileobj = request.files['upload'] fname, fext = os.path.splitext(fileobj.filename) rnd_name = '%s%s' % (gen_rnd_filename(), fext) filepath = os.path.join(app.static_folder, 'upload', rnd_name) # 检查路径是否存在,不存在则创建 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', filename='%s/%s' % ('upload', rnd_name)) else: error = 'post error' res = """ <script type="text/javascript"> window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s'); </script> """ % (callback, url, error) response = make_response(res) response.headers["Content-Type"] = "text/html" return response
上传文件的获取及保存部分比较简单,是标准的文件上传。这里主要讲讲上传成功后如何回调的问题。
CKEditor文件上传之后,服务端返回HTML文件,HTML文件包含JAVASCRIPT脚本,JS脚本会调用一个回调函数,若无错误,回调函数将返回的URL转交给CKEditor处理。
这3个参数依次是:
- CKEditorFuncNum : 回调函数序号。CKEditor通过URL参数提交给服务端
- URL : 上传后文件的URL
- Error : 错误信息。若无错误,返回空字符串
使用蓝本
在大型应用中经常会使用蓝本,在蓝本视图中集成CKEditor的步骤和app视图基本相同。
1. 创建蓝本时需指明蓝本static目录的绝对路径
demo = Blueprint('demo', static_folder="/path/to/static")
2. 对应url需加上蓝本端点
<script src="{{url_for('.static', filename='ckeditor/ckeditor.js')}}"></script> <script type="text/javascript"> CKEDITOR.replace( "ckeditor_demo", { filebrowserUploadUrl: './ckupload/' } ); </script>
3. 设置endpoint端点值
response = form.upload(endpoint=demo)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta
