xss 过滤

一. xss过滤

用户通过Form获取展示在终端, 提交数据,Form验证里面加入xss验证(对用户提交的内容验证是否有关键标签)
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [


    #写文章
    url(r'^test/', views.test),
    #查看写的文章
    url(r'^see/', views.see),


]
urls.py
from django.shortcuts import render,HttpResponse
from app01 import models

from app01.forms import ArticleForm

CONIENT = ""

def test(request):
    if request.method == "GET":
        obj = ArticleForm()
        return render(request,"test.html",{"obj":obj})
    else:
        obj = ArticleForm(request.POST)
        if obj.is_valid():
            content = obj.cleaned_data["content"]
            global CONIENT
            CONIENT = content
            print(content)
            return HttpResponse("...")


def see(request):
    return render(request,"see.html",{"con":CONIENT})
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form method="POST" action="/test/" novalidate>
        {% csrf_token %}

        <p>
            文章标题
            {{ obj.title }}
        </p>


        <div>
            <div>文章内容</div>
            <div>
                {{ obj.content|safe }}
            </div>
        </div>
        <input type="submit" value="提交">
    </form>
    <script src="/static/css/kindeditor-4.1.10/kindeditor-all.js"></script>

    <script>
        KindEditor.create("#id1",{
            "200px",
            height:"300px",
{#            //items:['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',#}
             //       'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
              //      'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                //    'superscript', 'clearhtml', 'quickformat'],
            //noDisableItems:['source', '|', 'undo'],     //保留某些item
            //designMode:false                            //其它注释

           //resizeType   改变窗口大小
            uploadJson:"/upload_img.html",  //上传文件
            extraFileUploadParams:{         //上传文件时携带token
                "csrfmiddlewaretoken":"{{ csrf_token }}"
            }
        })
    </script>

</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ con | safe }}
</body>
</html>
see.html
from django import forms
from django.forms import fields,Form
from django.forms import widgets



class ArticleForm(Form):
    title = fields.CharField(max_length=64)
    content = fields.CharField(
        widget=widgets.Textarea(attrs={"id":"id1"})
    )

    def clean_content(self):

        valid_tag = {
            "p": ["class", "id"],
            "img": ["src"],
            "div": ["class"],
        }


        from bs4 import BeautifulSoup
        old = self.cleaned_data["content"]
        soup = BeautifulSoup(old, "html.parser")

        tags = soup.find_all()
        for tag in tags:
            if tag.name not in valid_tag:
                tag.decompose()
            if tag.attrs:
                # print(tag.attrs)        #获取所有标签的属性
                for k in list(tag.attrs.keys()):
                    if k not in valid_tag[tag.name]:
                        del tag.attrs[k]
        content_str = soup.decode()

        return content_str
forms.py

二.以后用法 

#根据上面修改
from django import forms
from django.forms import fields,Form
from django.forms import widgets



class ArticleForm(Form):
    title = fields.CharField(max_length=64)
    content = fields.CharField(
        widget=widgets.Textarea(attrs={"id":"id1"})
    )

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

        return xss(old)
forms.py
from bs4 import BeautifulSoup

def xss(old):

    valid_tag = {
        "p": ["class", "id"],
        "img": ["src"],
        "div": ["class"],
    }

    soup = BeautifulSoup(old, "html.parser")

    tags = soup.find_all()
    for tag in tags:
        if tag.name not in valid_tag:
            tag.decompose()
        if tag.attrs:
            # print(tag.attrs)        #获取所有标签的属性
            for k in list(tag.attrs.keys()):
                if k not in valid_tag[tag.name]:
                    del tag.attrs[k]
    content_str = soup.decode()

    return content_str
utils/xss.py

  

原文地址:https://www.cnblogs.com/golangav/p/7213964.html