KindEditor

KindEditor

 前端插件:CKEditor,TinyEditor,UEEditor,KindEditor
 1.  安装: pip3 install beautifulsoup4
 2.  下载: http://files.cnblogs.com/files/wupeiqi/kindeditor_a5.zip 
     参考:http://www.cnblogs.com/wupeiqi/articles/6307554.html
     官网:http://kindeditor.net/docs/option.html
   kindeditor.js   没有引用plugins中的外部插件
   kindeditor-all.js   引用了plugins中的外部插件


requests.post(
   url='http://127.0.0.1:8000/wangzhe.html',
   data={
    'username':'xxxxxxxx'
   }
  )
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form method="POST" action="/wangzhe.html" novalidate>
        {% csrf_token %}
        <p>
            文章标题
            {{ obj.title }}
        </p>

        <div>
            <div>文章内容</div>
            <div>
                {{ obj.content }}
            </div>
        </div>
        <input type="submit" value="提交" />
    </form>
    <script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
    <!--导入kindeditor插件-->
    <script>
        KindEditor.create("#i1",{   //将#i1的标签变成副文本编辑框
             "700px",//宽度可以百分比
            height: "300px",
            items:[xxxx] //显示工具
            designMode:false,
            noDisableItems:[xxxx]//禁止使用的工具,配合designMode使用
            htmlTags:{xx}  //前端过滤关键词
            resizeType:1,//2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动。默认2,
            uploadJson: '/upload_img.html',  //上传文件的url
            extraFileUploadParams:{  //上传图片、Flash、视音频、文件时,支持添加别的参数一并传到服务器。
                "csrfmiddlewaretoken":"{{ csrf_token }}"
            }
            filePostName:fafafa,//上传文件的句柄
        })
    </script>

</body>
</html>
CONTENT = ""
from app01.forms import ArticleForm
def wangzhe(request):
    if request.method == "GET":
        obj = ArticleForm()
        return render(request,'wangzhe.html',{'obj':obj})
    else:
        obj = ArticleForm(request.POST)
        if obj.is_valid():
            content = obj.cleaned_data['content']
            global CONTENT
            CONTENT = content
            print(content)
            return HttpResponse('...')


def see(request):

    return render(request,'see.html',{'con': CONTENT})

    
    
#KindEditor上传文件    
def upload_img(request):
    import os
    upload_type = request.GET.get('dir')   #获取上传文件的类型
    file_obj = request.FILES.get('imgFile')
    file_path = os.path.join('static/imgs',file_obj.name)
    with open(file_path,'wb') as f:
        for chunk in file_obj.chunks():
            f.write(chunk)
    
    #返回这个字典,能实现文件的预览
    dic = {
        'error': 0,
        'url': '/' + file_path,
        'message': '错误了...'
    }
    import json
    return HttpResponse(json.dumps(dic))

防止xss注入:

content = """
<p id='i1' a='123' b='999'>
    <script>alert(123)</script>
</p>

<p id='i2'>
    <div>
        <p>asdfasdf</p>
    </div>
    <img id='i3' src="/static/imgs6.jpg" alt="" />
</p>
"""

# pip3 install beautifulsoup4
from bs4 import BeautifulSoup   #处理html标签的模块

valid_tag = {   #标签白名单
    'p': ['class','id'],
    'img':['src'],
    'div': ['class']
}

soup = BeautifulSoup(content,'html.parser')   #html.parser内置的解析器,将html标签解析为对象

tags = soup.find_all(name = "P")  #查找所有的p标签
tags = soup.find_all()  #遍历所有的标签
for tag in tags:
    if tag.name not in valid_tag:   #tag.name  标签名
        tag.clear()   #清空标签内容
         tag.decompose()   #删除标签
    if tag.attrs:          #tag.attrs是字典类型    
        for k in list(tag.attrs.keys()): # {id:'i1',a=123,b=999}
            if k not in valid_tag[tag.name]:
                del tag.attrs[k]   #删掉不符合白名单属性的属性
content_str = soup.decode()   #soup.decode()  将对象变成字符串
print(content_str)
# v = soup.find(name='p',attrs={'id':'i2'})   #以属性和标签类型找标签,可以分开用
# print(v)
知识点
from bs4 import BeautifulSoup

def xss(old):
    valid_tag = {
        'p': ['class','id'],
        'img':['src'],
        'div': ['class']
    }

    soup = BeautifulSoup(old,'html.parser')   #html.parser内置的解析器,将html标签解析为对象

    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()): # {id:'i1',a=123,b=999}
                if k not in valid_tag[tag.name]:
                    del tag.attrs[k]
    content_str = soup.decode()
    return content_str
封装的xss过滤插件
class ArticleForm(Form):

    title = fields.CharField(max_length=64)

    content = fields.CharField(
        widget=widgets.Textarea(attrs={'id':'i1'})
    )

    def clean_content(self):
        old = self.cleaned_data['content']
        from utils.xss import xss

        return xss(old)
后端引入应用
原文地址:https://www.cnblogs.com/domestique/p/7208995.html