Python的Flask框架中集成CKeditor富文本編輯器的教程
CKeditor是目前最優(yōu)秀的可見即可得網(wǎng)頁(yè)編輯器之一,它采用JavaScript編寫。具備功能強(qiáng)大、配置容易、跨瀏覽器、支持多種編程語言、開源等特點(diǎn)。它非常流行,互聯(lián)網(wǎng)上很容易找到相關(guān)技術(shù)文檔,國(guó)內(nèi)許多WEB項(xiàng)目和大型網(wǎng)站均采用了CKeditor。
下載CKeditor
訪問CKeditor官方網(wǎng)站,進(jìn)入下載頁(yè)面,選擇Standard Package(一般情況下功能足夠用了),然后點(diǎn)擊Download CKEditor按鈕下載ZIP格式的安裝文件。如果你想嘗試更多的功能,可以選擇下載Full Package。
下載好CKeditor之后,解壓到Flask項(xiàng)目static/ckeditor目錄即可。
在Flask項(xiàng)目中使用CKeditor
在Flask項(xiàng)目中使用CKeditor只需要執(zhí)行兩步就可以了:
在<script>標(biāo)簽引入CKeditor主腳本文件??梢砸氡镜氐奈募部梢砸肅DN上的文件。
使用CKEDITOR.replace()把現(xiàn)存的<textarea>標(biāo)簽替換成CKEditor。
示例代碼:
<!DOCTYPE html> <html> <head> <title>A Simple Page with CKEditor</title> <!-- 請(qǐng)確保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"> // 使用默認(rèn)配置 CKEDITOR.replace('editor1'); </script> </form> </body> </html>
因?yàn)镃Keditor足夠優(yōu)秀,所以第二步也可只為<textarea>追加名為ckeditor的class屬性值,CKeditor就會(huì)自動(dòng)將其替換。例如:
<!DOCTYPE html> <html> <head> <title>A Simple Page with CKEditor</title> <!-- 請(qǐng)確保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上的文件,下面給出幾個(gè)參考鏈接:
<script src="http://cdn.ckeditor.com/4.4.6/basic/ckeditor.js"></script>
基礎(chǔ)版(迷你版)
<script src="http://cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>
標(biāo)準(zhǔn)版
<script src="http://cdn.ckeditor.com/4.4.6/full/ckeditor.js"></script>
完整版
開啟上傳功能
默認(rèn)配置下,CKEditor是沒有開啟上傳功能的,要開啟上傳功能,也相當(dāng)?shù)暮?jiǎn)單,只需要簡(jiǎn)單修改配置即可。下面來看看幾個(gè)相關(guān)的配置值:
- filebrowserUploadUrl :文件上傳路徑。若設(shè)置了,則上傳按鈕會(huì)出現(xiàn)在鏈接、圖片、Flash對(duì)話窗口。
- filebrowserImageUploadUrl : 圖片上傳路徑。若不設(shè)置,則使用filebrowserUploadUrl值。
- filebrowserFlashUploadUrl : Flash上傳路徑。若不設(shè)置,則使用filebrowserUploadUrl值。
為了方便,這里我們只設(shè)置filebrowserUploadUrl值,其值設(shè)為/ckupload/(后面會(huì)在Flask中定義這個(gè)URL)。
設(shè)置配置值主要使用2種方法:
方法1:通過CKEditor根目錄的配置文件config.js來設(shè)置:
CKEDITOR.editorConfig = function( config ) { // ... // file upload url config.filebrowserUploadUrl = '/ckupload/'; // ... };
方法2:將設(shè)置值放入作為參數(shù)放入CKEDITOR.replace():
<script> CKEDITOR.replace('editor1', { filebrowserUploadUrl: '/ckupload/', }); </script>
Flask處理上傳請(qǐng)求
CKEditor上傳功能是統(tǒng)一的接口,即一個(gè)接口可以處理圖片上傳、文件上傳、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) # 檢查路徑是否存在,不存在則創(chuàng)建 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
上傳文件的獲取及保存部分比較簡(jiǎn)單,是標(biāo)準(zhǔn)的文件上傳。這里主要講講上傳成功后如何回調(diào)的問題。
CKEditor文件上傳之后,服務(wù)端返回HTML文件,HTML文件包含JAVASCRIPT腳本,JS腳本會(huì)調(diào)用一個(gè)回調(diào)函數(shù),若無錯(cuò)誤,回調(diào)函數(shù)將返回的URL轉(zhuǎn)交給CKEditor處理。
這3個(gè)參數(shù)依次是:
- CKEditorFuncNum : 回調(diào)函數(shù)序號(hào)。CKEditor通過URL參數(shù)提交給服務(wù)端
- URL : 上傳后文件的URL
- Error : 錯(cuò)誤信息。若無錯(cuò)誤,返回空字符串
使用藍(lán)本
在大型應(yīng)用中經(jīng)常會(huì)使用藍(lán)本,在藍(lán)本視圖中集成CKEditor的步驟和app視圖基本相同。
1. 創(chuàng)建藍(lán)本時(shí)需指明藍(lán)本static目錄的絕對(duì)路徑
demo = Blueprint('demo', static_folder="/path/to/static")
2. 對(duì)應(yīng)url需加上藍(lán)本端點(diǎn)
<script src="{{url_for('.static', filename='ckeditor/ckeditor.js')}}"></script> <script type="text/javascript"> CKEDITOR.replace( "ckeditor_demo", { filebrowserUploadUrl: './ckupload/' } ); </script>
3. 設(shè)置endpoint端點(diǎn)值
response = form.upload(endpoint=demo)
- 使用Flask集成bootstrap的方法
- Python的Flask站點(diǎn)中集成xhEditor文本編輯器的教程
- Python 利用flask搭建一個(gè)共享服務(wù)器的步驟
- 如何使用 Flask 做一個(gè)評(píng)論系統(tǒng)
- 如何基于Python和Flask編寫Prometheus監(jiān)控
- Docker構(gòu)建python Flask+ nginx+uwsgi容器
- 手把手教你將Flask應(yīng)用封裝成Docker服務(wù)的實(shí)現(xiàn)
- flask開啟多線程的具體方法
- 如何解決flask修改靜態(tài)資源后緩存文件不能及時(shí)更改問題
- Flask中sqlalchemy模塊的實(shí)例用法
- Python Flask異步發(fā)送郵件實(shí)現(xiàn)方法解析
- python的flask框架難學(xué)嗎
- flask項(xiàng)目集成swagger的方法
相關(guān)文章
python深度學(xué)習(xí)tensorflow入門基礎(chǔ)教程示例
這篇文章主要為大家介紹了python深度學(xué)習(xí)tensorflow入門基礎(chǔ)教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06python matplotlib繪圖實(shí)現(xiàn)刪除重復(fù)冗余圖例的操作
這篇文章主要介紹了python matplotlib繪圖實(shí)現(xiàn)刪除重復(fù)冗余圖例的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04使用Python給PDF添加目錄書簽的實(shí)現(xiàn)方法
有時(shí)下載到掃描版的 PDF 是不帶書簽?zāi)夸浀?這樣閱讀起來很不方便,下面通過 python 實(shí)現(xiàn)一個(gè)半自動(dòng)化添加書簽?zāi)夸浀哪_本,文中通過代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-10-10