〖Web〗-- KindEditor

【KindEditor】

一、前言

  我们在利用Form表单创建一个文本框的时候,它就仅仅是一个文本框!但是我们浏览别人页面的时候,在文本框上有很多的插件共我们点,点,点(重要的事情说三遍!!!)。很羡慕有没有?其实都是用一个叫做KindEditor的插件完成的!这次我们就说说这个可以让我们为所欲为点点点的插件!

  KindEditor是一款用Javascript编写的开源在线HTML编辑器,主要目的是让用户在网站上获得可见即可得的编辑效果,开发人员可以用 KindEditor 把传统的多行文本输入框(textarea)替换为可视化的富文本输入框。你可以在其官网了解更多信息,包括演示、文档、下载等。

二、KindEditor说明(注意它是个插件!!!)

1、进入官网

2、下载 --------->  官网下载

3、文件夹说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
├── 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主题

  由于KindEditor是一个插件,它兼容所有的语言,所以在这个插件中有很多别的语言的兼容包,所以说你要用那个就留下什么就可以了!这样还可以减少占用!

4、基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<textarea name="content" id="content"></textarea>
 
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
    initKindEditor();
});
 
function initKindEditor() {
    var kind = KindEditor.create('#content', {
     '100%'// 文本框宽度(可以百分比或像素)
    height: '300px'// 文本框高度(只能像素)
    minWidth: 200, // 最小宽度(数字)
    minHeight: 400 // 最小高度(数字)
});
}
</script>

5、详细参数

     http://kindeditor.net/docs/option.html

6、上传文件示例:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<div>
    <h1>文章内容</h1>
    {{ request.POST.content|safe }}
</div>


<form method="POST">
    <h1>请输入内容:</h1>
    {% csrf_token %}
    <div style=" 500px; margin: 0 auto;">
        <textarea name="content" id="content"></textarea>
    </div>
    <input type="submit" value="提交"/>
</form>

<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
    $(function () {
        initKindEditor();
    });

    function initKindEditor() {
        var a = 'kind';
        var kind = KindEditor.create('#content', {
             '100%',       // 文本框宽度(可以百分比或像素)
            height: '300px',     // 文本框高度(只能像素)
            minWidth: 200,       // 最小宽度(数字)
            minHeight: 400,      // 最小高度(数字)
            uploadJson: '/kind/upload_img/',
            extraFileUploadParams: {
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            fileManagerJson: '/kind/file_manager/',
            allowPreviewEmoticons: true,
            allowImageUpload: true
        });
    }
</script>
</body>
</html>
HTML
import os
import json
import time

from django.shortcuts import render
from django.shortcuts import HttpResponse


def index(request):
    """
    首页
    :param request:
    :return:
    """
    return render(request, 'index.html')


def upload_img(request):
    """
    文件上传
    :param request:
    :return:
    """
    dic = {
        'error': 0,
        'url': '/static/imgs/20130809170025.png',
        'message': '错误了...'
    }

    return HttpResponse(json.dumps(dic))


def file_manager(request):
    """
    文件管理
    :param request:
    :return:
    """
    dic = {}
    root_path = '/Users/wupeiqi/PycharmProjects/editors/static/'
    static_root_path = '/static/'
    request_path = request.GET.get('path')
    if request_path:
        abs_current_dir_path = os.path.join(root_path, request_path)
        move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
        dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path

    else:
        abs_current_dir_path = root_path
        dic['moveup_dir_path'] = ''

    dic['current_dir_path'] = request_path
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []
    for item in os.listdir(abs_current_dir_path):
        abs_item_path = os.path.join(abs_current_dir_path, item)
        a, exts = os.path.splitext(item)
        is_dir = os.path.isdir(abs_item_path)
        if is_dir:
            temp = {
                'is_dir': True,
                'has_file': True,
                'filesize': 0,
                'dir_path': '',
                'is_photo': False,
                'filetype': '',
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }
        else:
            temp = {
                'is_dir': False,
                'has_file': False,
                'filesize': os.stat(abs_item_path).st_size,
                'dir_path': '',
                'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
                'filetype': exts.lower().strip('.'),
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }

        file_list.append(temp)
    dic['file_list'] = file_list
    return HttpResponse(json.dumps(dic))
Views

7、XSS过滤特殊标签

  做这种可以用户交互的网页,一定要警惕WEB注入的问题!!!没准某人输入个什么字符串,直接导致服务器瘫痪!所以这些可以让用户输入的模块,一定要做过滤,对特殊标签或是对象的过滤!!!慎防注入问题!!!

处理依赖

1
pip3 install beautifulsoup4
from bs4 import BeautifulSoup

class XSSFilter(object):
    __instance = None

    def __init__(self):
        # XSS白名单
        self.valid_tags = {
            "font": ['color', 'size', 'face', 'style'],
            'b': [],
            'div': [],
            "span": [],
            "table": [
                'border', 'cellspacing', 'cellpadding'
            ],
            'th': [
                'colspan', 'rowspan'
            ],
            'td': [
                'colspan', 'rowspan'
            ],
            "a": ['href', 'target', 'name'],
            "img": ['src', 'alt', 'title'],
            'p': [
                'align'
            ],
            "pre": ['class'],
            "hr": ['class'],
            'strong': []
        }

    @classmethod
    def instance(cls):
        if not cls.__instance:
            obj = cls()
            cls.__instance = obj
        return cls.__instance

    def process(self, content):
        soup = BeautifulSoup(content, 'lxml')
        # 遍历所有HTML标签
        for tag in soup.find_all(recursive=True):
            # 判断标签名是否在白名单中
            if tag.name not in self.valid_tags:
                tag.hidden = True
                if tag.name not in ['html', 'body']:
                    tag.hidden = True
                    tag.clear()
                continue
            # 当前标签的所有属性白名单
            attr_rules = self.valid_tags[tag.name]
            keys = list(tag.attrs.keys())
            for key in keys:
                if key not in attr_rules:
                    del tag[key]

        return soup.renderContents()


if __name__ == '__main__':
    html = """<p class="title">
                        <b>The Dormouse's story</b>
                    </p>
                    <p class="story">
                        <div name='root'>
                            Once upon a time there were three little sisters; and their names were
                            <a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
                            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
                            <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
                            and they lived at the bottom of a well.
                            <script>alert(123)</script>
                        </div>
                    </p>
                    <p class="story">...</p>"""

    v = XSSFilter.instance().process(html)
    print(v)
XSS示例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup


class XSSFilter(object):
    __instance = None

    def __init__(self):
        # XSS白名单
        self.valid_tags = {
            "font": ['color', 'size', 'face', 'style'],
            'b': [],
            'div': [],
            "span": [],
            "table": [
                'border', 'cellspacing', 'cellpadding'
            ],
            'th': [
                'colspan', 'rowspan'
            ],
            'td': [
                'colspan', 'rowspan'
            ],
            "a": ['href', 'target', 'name'],
            "img": ['src', 'alt', 'title'],
            'p': [
                'align'
            ],
            "pre": ['class'],
            "hr": ['class'],
            'strong': []
        }

    def __new__(cls, *args, **kwargs):
        """
        单例模式
        :param cls:
        :param args:
        :param kwargs:
        :return:
        """
        if not cls.__instance:
            obj = object.__new__(cls, *args, **kwargs)
            cls.__instance = obj
        return cls.__instance

    def process(self, content):
        soup = BeautifulSoup(content, 'lxml')
        # 遍历所有HTML标签
        for tag in soup.find_all(recursive=True):
            # 判断标签名是否在白名单中
            if tag.name not in self.valid_tags:
                tag.hidden = True
                if tag.name not in ['html', 'body']:
                    tag.hidden = True
                    tag.clear()
                continue
            # 当前标签的所有属性白名单
            attr_rules = self.valid_tags[tag.name]
            keys = list(tag.attrs.keys())
            for key in keys:
                if key not in attr_rules:
                    del tag[key]

        return soup.renderContents()


if __name__ == '__main__':
    html = """<p class="title">
                        <b>The Dormouse's story</b>
                    </p>
                    <p class="story">
                        <div name='root'>
                            Once upon a time there were three little sisters; and their names were
                            <a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
                            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
                            <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
                            and they lived at the bottom of a well.
                            <script>alert(123)</script>
                        </div>
                    </p>
                    <p class="story">...</p>"""

    obj = XSSFilter()
    v = obj.process(html)
    print(v)
基于__new__实现单例模式示例

三、项目实用 ----> 写一张自己的博客!

class ArticleForm(Form):
    title = fields.CharField(
        max_length=64,
        widget=widgets.TextInput)

    content = fields.CharField(
        widget=widgets.Textarea(
            attrs={"id":"texts"},),)

    article_type_id = fields.ChoiceField(
        widget=widgets.RadioSelect(attrs={"class":"ulstyle",}),
    )
    category_id = fields.ChoiceField(
        widget=widgets.RadioSelect(attrs={"class":"ulstyle",},),
    )
    tag_id = fields.MultipleChoiceField(
        widget=widgets.CheckboxSelectMultiple(attrs={"class":"ulstyle",},),
    )

    def __init__(self,*args,**kwargs):
        super(ArticleForm,self).__init__(*args,**kwargs)
        self.fields["article_type_id"].choices=models.Article.type_choices
        self.fields["category_id"].choices=models.Category.objects.values_list("nid","title")
        self.fields["tag_id"].choices=models.Tag.objects.values_list("nid","title")

    def clean_content(self):
        old = self.cleaned_data["content"]
        return xss(old)
Form组件(包含敏感字符过滤)
url(r'^creates.html$', views.creates, name="creates"),
路由url
def creates(request):
    """
    创建新文章
    :param request:
    :return:
    """
    if request.method == "GET":
        obj = ArticleForm()
        return render(request,"create_page.html",{"obj":obj})
    else:
        obj = ArticleForm(request.POST)
        if obj.is_valid():
            # blog_id = request.session.get("users")["blog__nid"]

            # 仅是测试使用
            blog = models.Blog.objects.filter(user__nid=1).first()

            content = obj.cleaned_data.pop("content")
            tag_id = obj.cleaned_data.pop("tag_id")
            summary = "%s..."%(content[0:31])
            obj.cleaned_data["blog_id"] = blog.nid
            obj.cleaned_data["summary"] = summary

            newacticles = models.Article.objects.create(**obj.cleaned_data)
            models.ArticleDetail.objects.create(content=content,article_id=newacticles.nid)
            atc2tag = [models.Article2Tag(article_id=newacticles.nid, tag_id=i) for i in tag_id]
            models.Article2Tag.objects.bulk_create(*atc2tag)
            return redirect(reverse("mpages",args=[blog.nid,0,0,0]))
        else:
            return render(request,"create_page.html",{"obj":obj})
Views视图函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/css/createpages.css">
    <script src="/static/plugins/kindeditor/kindeditor-all.js"></script>
</head>
<body>
<form method="POST" action="{% url "creates" %}" novalidate>
    {% csrf_token %}
    <p><span>文章标题:</span>{{ obj.title }}<span>{{ obj.errors.tit.0 }}</span></p>
    <p>文章内容:</p>
    <p>{{ obj.content }}<span>{{ obj.errors.content.0 }}</span></p>
    <p><span>大大分类:</span>{{ obj.article_type_id }}</p>
    <p><span>文章分类:</span>{{ obj.category_id }}</p>
    <p><span>文章标签:</span>{{ obj.tag_id }}</p>
    <p><input type="submit" value="提交"></p>
</form>
<script>
    KindEditor.create("#texts",{
        "100%",
        height:"500px",
        resizeType:2,   //用于改变文本框大小的样式
        uploadJson:"/upload_images/", //图片上传地址
        extraFileUploadParams:{
             csrfmiddlewaretoken:"{{ csrf_token }}"
        },//添加额外要提交的数据
        filePostName: 'files' //定义提交的数据名为files
    });
</script>
</body>
</html>
HTML模版页面
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

#字符串敏感信息过滤模块,常用于form组件,对输入信息的认证
from bs4 import BeautifulSoup

def xss(old):
    valid_tag={
        "p":['class','id'],
        "img":['src'],
        'div':['class']
    }#定义白名单 '标签名':['属性']
    soup = BeautifulSoup(old,'html.parser') #把字符串以标签名为单位转换成一个个的对象,操作字符串及方法  html.parser是Django内部自有的检测引擎
    tags = soup.find_all() #获取所有的标签对象 --深度优先
    for tag in tags:
        if tag.name not in valid_tag:
            tag.decompose()  #出现没在白名单内的对象,就直接把这个标签删除
        if tag.attrs: #如果对象有属性的话做属性判断 ---->注意属性是字典类型
            for k in list(tag.attrs.keys()): #获取属性的key
                if k not in valid_tag[tag.name]:  #如果对象的属性属于白名单内
                    del tag.attrs[k]  #删除该条属性
    content_str = soup.decode() # 把对象转码成字符串类型
    return content_str
XSS字段过滤方法

四、个人总结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
创建KindEditor文本框类型方法:   
    语法结构:
    导入模块之后,会有一个KindEditor对象,利用这个对象对text文本输入框进行改造。
    KindEditor.create("文本框id或class名,能找到就行",{样式})
    常用样式包括:
         "700px",  宽度
        height: "300px", 高度
        items: 要显示的工具 (默认是全部)
        resizeType:1, 用于改变文本框大小的样式,2102时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动。
        uploadJson: '/upload_img.html',  上传文件指定的url路由地址
        extraFileUploadParams:{
            "csrfmiddlewaretoken":"{{ csrf_token }}"  上传文件额外提交的信息
        },
        filePostName: 'fafafa'  为POST方式提交的文件对象重命名      
         
         
         
利用soup实现对输入内容的过滤操作
 
注意写白名单,允许某些标签通过。若是写黑名单则需要顺势更改还不如直接写白名单方便。      
 Beautifulsoup4
    先导入后创建对象,利用对象下的方法实现操作
    from bs4 import BeautifulSoup
    soup = BeautifulSoup('要操作的字符串','html.parser'-->htmlparser是搜索引擎,用于html解析和分析的工具
        注意:这种操作是把字符串转换成以标签为单位的一个一个对象,对象套对象,完全是对象来操作。
         
    - find() --- 找一个标签,属性有name="标签名" 指找是该标签名的标签,attrs={"id":"值"}也可以通过属性去查找,也可以两者同时存在组成与的关系,共同查找
    - find_all()  找所有标签,和找一个的参数一致,但结果是找到所有匹配的标签,查找顺序是以深度优先
     
    查找操作中使用的不同参数
        - attrs   del attrs[xx] 
        - name
    删除敏感标签的话,有以下两种方法:
        - decompose  .decompose() 简单粗暴的把整个标签删除
        - clear    .clear() 清除该标签内的内容 不删除标签
     
    所有数据处理完之后,需要把对象转换成其他类型的转码方式:
        - decode() soup对象转换成字符串
        - encode() soup对象转换成字节 
原文地址:https://www.cnblogs.com/SHENGXIN/p/8093755.html