KindEditor

1. 官网

2. 下载

3. 文件目录说明

├── asp                        asp示例
├── asp.net                    asp.net示例
├── attached                   空文件夹,放置关联文件attached
├── examples                   HTML示例
├── jsp                        java示例
├── kindeditor-all-min.js      全部JS(压缩)
├── kindeditor-all.js          全部JS(未压缩)
├── kindeditor-min.js          仅KindEditor JS(压缩)
├── kindeditor.js              仅KindEditor JS(未压缩)
├── lang                       支持语言
├── license.txt                License
├── php                        PHP示例
├── plugins                    KindEditor内部使用的插件
└── themes                     KindEditor主题

4. 基本使用

<!-- 1.在需要显示编辑器的位置添加textarea输入框 -->
<textarea name="content" id="content"></textarea>

<!-- 2.在该HTML页面引入js -->
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kindeditor-4.1.10/kindeditor-all.js"></script>
<script src=/static/plugins/kindeditor-4.1.10/lang/zh-CN.js"></script>

<!-- 3.编写脚本 -->
<script>
    $(function () {
        initKindEditor();

        // 取得HTML内容
        html = kind.html();
    });
 
    function initKindEditor() {
        
        var kind = KindEditor.create('#content', {
             '100%',       // 文本框宽度(可以百分比或像素)
            height: '300px',     // 文本框高度(只能像素)
            minWidth: 200,       // 最小宽度(数字)
            minHeight: 400,       // 最小高度(数字)

            cssPath : '/css/index.css',
            filterMode : true, 
        });
    }
</script>

5. 详细参数

6. 开发文档

7. 上传文件示例

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 
 9 <div>
10     <h1>文章内容</h1>
11     {{ request.POST.content|safe }}
12 </div>
13 
14 
15 <form method="POST">
16     <h1>请输入内容:</h1>
17     {% csrf_token %}
18     <div style=" 500px; margin: 0 auto;">
19         <textarea name="content" id="content"></textarea>
20     </div>
21     <input type="submit" value="提交"/>
22 </form>
23 
24 <script src="/static/jquery-1.12.4.js"></script>
25 <script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
26 <script>
27     $(function () {
28         initKindEditor();
29     });
30 
31     function initKindEditor() {
32         var a = 'kind';
33         var kind = KindEditor.create('#content', {
34              '100%',       // 文本框宽度(可以百分比或像素)
35             height: '300px',     // 文本框高度(只能像素)
36             minWidth: 200,       // 最小宽度(数字)
37             minHeight: 400,      // 最小高度(数字)
38             uploadJson: '/kind/upload_img/',
39             extraFileUploadParams: {
40                 'csrfmiddlewaretoken': '{{ csrf_token }}'
41             },
42             fileManagerJson: '/kind/file_manager/',
43             allowPreviewEmoticons: true,
44             allowImageUpload: true
45         });
46     }
47 </script>
48 </body>
49 </html>
html文件内容
 1 import os
 2 import json
 3 import time
 4 from django.shortcuts import render
 5 from django.shortcuts import HttpResponse
 6 
 7 
 8 def index(request):
 9     """
10     首页
11     :param request:
12     :return:
13     """
14     return render(request, 'index.html')
15 
16 
17 def upload_img(request):
18     """
19     文件上传
20     :param request:
21     :return:
22     """
23     dic = {
24         'error': 0,
25         'url': '/static/imgs/20130809170025.png',
26         'message': '错误了...'
27     }
28 
29     return HttpResponse(json.dumps(dic))
30 
31 
32 def file_manager(request):
33     """
34     文件管理
35     :param request:
36     :return:
37     """
38     dic = {}
39     root_path = '/Users/Halo/PycharmProjects/editors/static/'
40     static_root_path = '/static/'
41     request_path = request.GET.get('path')
42     if request_path:
43         abs_current_dir_path = os.path.join(root_path, request_path)
44         move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
45         dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path
46 
47     else:
48         abs_current_dir_path = root_path
49         dic['moveup_dir_path'] = ''
50 
51     dic['current_dir_path'] = request_path
52     dic['current_url'] = os.path.join(static_root_path, request_path)
53 
54     file_list = []
55     for item in os.listdir(abs_current_dir_path):
56         abs_item_path = os.path.join(abs_current_dir_path, item)
57         a, exts = os.path.splitext(item)
58         is_dir = os.path.isdir(abs_item_path)
59         if is_dir:
60             temp = {
61                 'is_dir': True,
62                 'has_file': True,
63                 'filesize': 0,
64                 'dir_path': '',
65                 'is_photo': False,
66                 'filetype': '',
67                 'filename': item,
68                 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
69             }
70         else:
71             temp = {
72                 'is_dir': False,
73                 'has_file': False,
74                 'filesize': os.stat(abs_item_path).st_size,
75                 'dir_path': '',
76                 'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
77                 'filetype': exts.lower().strip('.'),
78                 'filename': item,
79                 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
80             }
81 
82         file_list.append(temp)
83     dic['file_list'] = file_list
84     return HttpResponse(json.dumps(dic))
views.py

8. XSS过滤特殊标签

BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单。

安装:pip3 install beautifulsoup4

 1 from bs4 import BeautifulSoup
 2 
 3 
 4 class XSSFilter(object):
 5     __instance = None
 6 
 7     def __init__(self):
 8         # XSS白名单
 9         self.valid_tags = {
10             "font": ['color', 'size', 'face', 'style'],
11             'b': [],
12             'div': [],
13             "span": [],
14             "table": [
15                 'border', 'cellspacing', 'cellpadding'
16             ],
17             'th': [
18                 'colspan', 'rowspan'
19             ],
20             'td': [
21                 'colspan', 'rowspan'
22             ],
23             "a": ['href', 'target', 'name'],
24             "img": ['src', 'alt', 'title'],
25             'p': [
26                 'align'
27             ],
28             "pre": ['class'],
29             "hr": ['class'],
30             'strong': []
31         }
32 
33     @classmethod
34     def instance(cls):
35         if not cls.__instance:
36             obj = cls()
37             cls.__instance = obj
38         return cls.__instance
39 
40     def process(self, content):
41         soup = BeautifulSoup(content, 'lxml')
42         # 遍历所有HTML标签
43         for tag in soup.find_all(recursive=True):
44             # 判断标签名是否在白名单中
45             if tag.name not in self.valid_tags:
46                 tag.hidden = True
47                 if tag.name not in ['html', 'body']:
48                     tag.hidden = True
49                     tag.clear()
50                 continue
51             # 当前标签的所有属性白名单
52             attr_rules = self.valid_tags[tag.name]
53             keys = list(tag.attrs.keys())
54             for key in keys:
55                 if key not in attr_rules:
56                     del tag[key]
57 
58         return soup.renderContents()
59 
60 
61 if __name__ == '__main__':
62     html = """<p class="title">
63                         <b>The Dormouse's story</b>
64                     </p>
65                     <p class="story">
66                         <div name='root'>
67                             Once upon a time there were three little sisters; and their names were
68                             <a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
69                             <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
70                             <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
71                             and they lived at the bottom of a well.
72                             <script>alert(123)</script>
73                         </div>
74                     </p>
75                     <p class="story">...</p>"""
76 
77     v = XSSFilter.instance().process(html)
78     print(v)
xss示例
 1 from bs4 import BeautifulSoup
 2 
 3 
 4 class XSSFilter(object):
 5     __instance = None
 6 
 7     def __init__(self):
 8         # XSS白名单
 9         self.valid_tags = {
10             "font": ['color', 'size', 'face', 'style'],
11             'b': [],
12             'div': [],
13             "span": [],
14             "table": [
15                 'border', 'cellspacing', 'cellpadding'
16             ],
17             'th': [
18                 'colspan', 'rowspan'
19             ],
20             'td': [
21                 'colspan', 'rowspan'
22             ],
23             "a": ['href', 'target', 'name'],
24             "img": ['src', 'alt', 'title'],
25             'p': [
26                 'align'
27             ],
28             "pre": ['class'],
29             "hr": ['class'],
30             'strong': []
31         }
32 
33     def __new__(cls, *args, **kwargs):
34         """
35         单例模式
36         :param cls:
37         :param args:
38         :param kwargs:
39         :return:
40         """
41         if not cls.__instance:
42             obj = object.__new__(cls, *args, **kwargs)
43             cls.__instance = obj
44         return cls.__instance
45 
46     def process(self, content):
47         soup = BeautifulSoup(content, 'lxml')
48         # 遍历所有HTML标签
49         for tag in soup.find_all(recursive=True):
50             # 判断标签名是否在白名单中
51             if tag.name not in self.valid_tags:
52                 tag.hidden = True
53                 if tag.name not in ['html', 'body']:
54                     tag.hidden = True
55                     tag.clear()
56                 continue
57             # 当前标签的所有属性白名单
58             attr_rules = self.valid_tags[tag.name]
59             keys = list(tag.attrs.keys())
60             for key in keys:
61                 if key not in attr_rules:
62                     del tag[key]
63 
64         return soup.renderContents()
65 
66 
67 if __name__ == '__main__':
68     html = """<p class="title">
69                         <b>The Dormouse's story</b>
70                     </p>
71                     <p class="story">
72                         <div name='root'>
73                             Once upon a time there were three little sisters; and their names were
74                             <a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
75                             <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
76                             <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
77                             and they lived at the bottom of a well.
78                             <script>alert(123)</script>
79                         </div>
80                     </p>
81                     <p class="story">...</p>"""
82 
83     obj = XSSFilter()
84     v = obj.process(html)
85     print(v)
基于__new__实现的单例模式示例
原文地址:https://www.cnblogs.com/yzls/p/9466976.html