近期做一个项目,要嵌入WangEditor富文本编辑器,不过编辑器并没有python的相关代码,需要根据文档来进行自己编写。

安装必要的依赖

  • Flask-Uploads 或其他类似包用于文件上传管理

python代码

下面代码配置了上传路径、文件类型、上传和回调数据、

from flask import Flask, render_template, request, jsonify, send_from_directory
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)

# 配置上传路径
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 上传、回调
@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'no file'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'no selected file'}), 400
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        return jsonify({'url': f"/uploads/{filename}"})
    else:
        return jsonify({'error': 'invalid file type'}), 400

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/edit/<int:article_id>', methods=['GET', 'POST'])
def edit_article(article_id):
    if request.method == 'POST':
        content = request.form.get('content')
        # Save or update article content to database here
        return jsonify({'status': 'success'})
    else:
        # 在此处从数据库中获取文章内容,就不写了。
        ......
        ......
        return render_template('editor.html', content=article_content)

if __name__ == '__main__':
    app.run(debug=True)

模版html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Article Editor</title>
    <!-- Include WangEditor CSS -->
    <link rel="stylesheet" href="//unpkg.com/wangeditor@latest/dist/css/wangEditor.min.css">
</head>
<body>
    <div id="editor"></div>

    <!-- Include WangEditor JS -->
    <script src="//unpkg.com/wangeditor@latest/dist/wangEditor.min.js"></script>
    <script>
        var E = window.wangEditor;
        var editor = new E('#editor');

        // 配置上传图片和视频服务器URL
        editor.config.uploadFileName = 'file';
        editor.config.uploadImgServer = '/upload';
        editor.config.uploadVideoServer = '/upload';

        // 编辑现有文章时设置初始内容 
        editor.txt.html(`{{ content|safe }}`);

        editor.create();

        // 添加事件监听器以处理表单提交
        document.querySelector('form').addEventListener('submit', function (event) {
            event.preventDefault();
            var content = editor.txt.html();
            fetch('/edit/{{ article_id }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'content': content,
                })
            }).then(response => response.json())
              .then(data => console.log(data));
        });
    </script>
</body>
</html>