Python3 + Django2.0 百度Ueditor 富文本編輯器的集成
百度富文本編輯器官網地址:http://fex.baidu.com/ueditor/
疑問:為什么要二次集成?
答案:因為百度富文本編輯器Ueditor沒有對python的支持
步驟1:
在官網下載Ueditor的任意版本代碼:http://ueditor.baidu.com/website/download.html#ueditor
步驟2:
將下載的代碼放入到 django 項目中
步驟3:前端引用
在前端HTML代碼中引用富文本編輯器【注意:此時因為還沒有實例化富文本編輯器,所以暫時無效果!!!】
<!-- 引用對應的js文件 --> <script type="text/javascript" charset="utf-8" src="{% static 'xxx/xxx/ueditor.config.js' %}"></script> <script type="text/javascript" charset="utf-8" src="{% static 'xxx/xxx/ueditor.all.min.js' %}"></script> <!-- 富文本編輯器 --> <div> <script id="uedit" type="text/plain></script> </div>
步驟6:js代碼
在前端引用之后,使用js實例化Ueditor,並且配置一些參數:
// 富文本編輯器處理方法 News.prototype.listenEditor = function () { // 實例化一個富文本編輯器 window.ue = UE.getEditor('editor', { 'initialFrameHeight': 400,//設置富文本編輯器的高度 //'serverUrl': '/ueditor/upload/', //設置文件上傳的視圖函數(服務器路徑) /* * initialFrameWidth:"100%":設置富文本 編輯器自適應寬度 * 也可以在:ueditor.config.js中修改initialFrameWidth 達到同樣的目的 */ initialFrameWidth:"100%" }); };
步驟6:軍事機密,django + python服務端的集成處理(直接復制就可以用了)
1> views.py 中邏輯代碼,還需要在settings進行對應的配置
# encoding: utf-8 """ 百度富文本編輯器python版本服務端集成代碼 """ import json import re import string import time import hashlib import random import base64 import sys import os from urllib import parse # from django.conf import settings from django.conf import settings from django.http import JsonResponse from django.shortcuts import reverse from django.views.decorators.csrf import csrf_exempt from django.http import FileResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.http import require_http_methods # 更改工作目錄。這么做的目的是七牛qiniu的sdk # 在設置緩存路徑的時候默認會設置到C:/Windows/System32下面 # 會造成沒有權限創建。 # os.chdir(os.path.dirname(__file__)) # 這個在我的項目中設置后,服務器啟動回報:manage.py 文件不存在,注釋后一切正常 try: import qiniu except: raise RuntimeError("3333333333") # pass from io import BytesIO # 七牛相關配置 UEDITOR_QINIU_ACCESS_KEY = "" UEDITOR_QINIU_SECRET_KEY = "" UEDITOR_QINIU_BUCKET_NAME = "" UEDITOR_QINIU_DOMAIN = "" # ueditor 富文本編輯器的 config.json 配置文件路徑 UEDITOR_CONFIG_PATH = "" # 配置文件上傳路徑 UEDITOR_UPLOAD_PATH = "" # 是否要將文件上傳到七牛 UEDITOR_UPLOAD_TO_QINIU = False # 是否要將文件上傳到自己的服務器 UEDITOR_UPLOAD_TO_SERVER = False # 用來判斷是否要將文件上傳到自己的服務器 try: UEDITOR_UPLOAD_TO_SERVER = settings.UEDITOR_UPLOAD_TO_SERVER if UEDITOR_UPLOAD_TO_SERVER: UEDITOR_UPLOAD_PATH = settings.UEDITOR_UPLOAD_PATH if not os.path.exists(UEDITOR_UPLOAD_PATH): os.mkdir(UEDITOR_UPLOAD_PATH) except Exception as e: os.chdir(os.path.join('..', '..', os.path.dirname(__file__))) raise RuntimeError("123"+os.getcwd()) # pass # 用來判斷是否要將文件上傳到七牛 try: UEDITOR_UPLOAD_TO_QINIU = settings.UEDITOR_UPLOAD_TO_QINIU except: raise RuntimeError("1111111111111111") # pass # 如果既沒有配置上傳到本地,又沒有配置上傳到七牛,那么就拋出異常 if not UEDITOR_UPLOAD_PATH and not UEDITOR_UPLOAD_TO_QINIU: raise RuntimeError("UEditor的UEDITOR_UPLOAD_TO_SERVER或者UEDITOR_UPLOAD_TO_QINIU必須配置一項!") # 判斷是否配置了config.json文件的路徑 try: UEDITOR_CONFIG_PATH = settings.UEDITOR_CONFIG_PATH except: raise RuntimeError("請配置UEditor的配置文件的路徑!") # 如果配置了七牛的配置信息 if UEDITOR_UPLOAD_TO_QINIU: try: UEDITOR_QINIU_ACCESS_KEY = settings.UEDITOR_QINIU_ACCESS_KEY UEDITOR_QINIU_SECRET_KEY = settings.UEDITOR_QINIU_SECRET_KEY UEDITOR_QINIU_BUCKET_NAME = settings.UEDITOR_QINIU_BUCKET_NAME UEDITOR_QINIU_DOMAIN = settings.UEDITOR_QINIU_DOMAIN except Exception as e: option = e.args[0] raise RuntimeError('請在app.config中配置%s!' % option) # # @method_decorator(decorator,name=''):將函數裝飾器轉換為類裝飾器 # @csrf_exempt:csrftoken裝飾器 # @require_http_methods(['GET','POST']):請求裝飾器,只允許 get 、 post 請求 # @method_decorator([csrf_exempt, require_http_methods(['GET', 'POST'])], name='dispatch') class UploadView(View): # 構造函數 def __init__(self): super(UploadView, self).__init__() def _random_filename(self, rawfilename): """ 隨機的文件名,保證文件名稱不會沖突 """ letters = string.ascii_letters random_filename = str(time.time()) + "".join(random.sample(letters, 5)) filename = hashlib.md5(random_filename.encode('utf-8')).hexdigest() subffix = os.path.splitext(rawfilename)[-1] return filename + subffix def _json_result(self, state='', url='', title='', original=''): """ 返回指定格式的json數據的 """ result = { 'state': state, 'url': url, 'title': title, 'original': original } return JsonResponse(result) def _upload_to_qiniu(self, upfile, filename): """ 上傳文件到七牛 """ if not sys.modules.get('qiniu'): raise RuntimeError('沒有導入qiniu模塊!') q = qiniu.Auth(UEDITOR_QINIU_ACCESS_KEY, UEDITOR_QINIU_SECRET_KEY) token = q.upload_token(UEDITOR_QINIU_BUCKET_NAME) buffer = BytesIO() for chunk in upfile.chunks(): buffer.write(chunk) buffer.seek(0) ret, info = qiniu.put_data(token, filename, buffer.read()) if info.ok: url = parse.urljoin(UEDITOR_QINIU_DOMAIN, ret['key']) return 'SUCCESS', url, ret['key'], ret['key'] else: return 'FAIL', None, None, None def _upload_to_server(self, upfile, filename): """ 上傳文件到自己的服務器 """ with open(os.path.join(UEDITOR_UPLOAD_PATH, filename), 'wb') as fp: for chunk in upfile.chunks(): fp.write(chunk) url = reverse("ueditor:send_file", kwargs={"filename": filename}) return 'SUCCESS', url, filename, filename def _action_config(self): """ 處理configl類型的響應 將配置文件以 json 格式返回給前端 """ config_path = UEDITOR_CONFIG_PATH with open(config_path, 'r', encoding='utf-8') as fp: result = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read())) return JsonResponse(result) def _action_upload(self, request): """ 處理文件(圖片,視頻,普通文件)上傳 """ upfile = request.FILES.get("upfile") filename = self._random_filename(upfile.name) qiniu_result = None server_result = None if UEDITOR_UPLOAD_TO_QINIU: qiniu_result = self._upload_to_qiniu(upfile, filename) if UEDITOR_UPLOAD_TO_SERVER: server_result = self._upload_to_server(upfile, filename) if qiniu_result and qiniu_result[0] == 'SUCCESS': return self._json_result(*qiniu_result) elif server_result and server_result[0] == 'SUCCESS': return self._json_result(*server_result) else: return self._json_result() def _action_scrawl(self, request): base64data = request.form.get("upfile") img = base64.b64decode(base64data) filename = self._random_filename('xx.png') with open(os.path.join(UEDITOR_UPLOAD_PATH, filename), 'wb') as fp: fp.write(img) url = reverse('ueditor:send_file', kwargs={"filename": filename}) return self._json_result('SUCCESS', url, filename, filename) # 類視圖入口函數 # 當請求該類視圖時,會優先執行此函數 # activate:文件類型 def dispatch(self, request, *args, **kwargs): super(UploadView, self).dispatch(request, *args, **kwargs) action = request.GET.get('action') if action == 'config': return self._action_config() elif action in ['uploadimage', 'uploadvideo', 'uploadfile']: return self._action_upload(request) elif action == 'uploadscrawl': return self._action_scrawl(request) else: return self._json_result() def send_file(request, filename): fp = open(os.path.join(UEDITOR_UPLOAD_PATH, filename), 'rb') response = FileResponse(fp) response['Content-Type'] = "application/octet-stream" return response
2> settings.py 中的配置
# """ # 百度UEditor富文本編輯配置 # """ # 是否要將文件上傳到七牛(必須) UEDITOR_UPLOAD_TO_QINIU = True # 是否要將文件上傳到自己的服務器(必須) UEDITOR_UPLOAD_TO_SERVER = False # 七牛相關配置(UEDITOR_UPLOAD_TO_QINIU:True:則必須進行配置,否則無須配置) UEDITOR_QINIU_ACCESS_KEY = "自己的ACCESS_KEY" UEDITOR_QINIU_SECRET_KEY = "自己的SECRET_KEY " UEDITOR_QINIU_BUCKET_NAME = "對象存儲空間名稱" # 域名 http://域名/ UEDITOR_QINIU_DOMAIN = "http://域名/" # config.json 配置文件路徑 # php版本的Ueditor config.json 路徑為:ueditor\utf8-php\php\config.json UEDITOR_CONFIG_PATH = os.path.join(BASE_DIR, 'front', 'dist', 'ueditor', 'utf8-php', 'php', 'config.json') # 配置文件上傳路徑(UEDITOR_UPLOAD_TO_SERVER:True:則必須進行配置,否則無須配置) # UEDITOR_UPLOAD_PATH = MEDIA_ROOT