zoukankan      html  css  js  c++  java
  • day99-django-避免xss攻击(跨站脚本攻击)

    #慎用|safe 和 mark_safe,如果要用,一定要过滤关键字

    from
    django.shortcuts import render lis = [] def content(request): if request.method == 'GET': return render(request,'form.html') else: content = request.POST.get('content') #因为html里面写了{{ i|safe }},如果i是<script>alert('abc')</script>, #那么浏览器就执行这个代码,就受到xss攻击。所以在这里要过滤掉script。 if 'script' in content: return render(request, 'form.html',{'error':'傻逼,想黑我'}) else: lis.append(content) return render(request, 'form.html') def comment(request): return render(request,'comment.html',{'lis':lis}) #模板替换前,标签要使用mark_safe标记,否则在浏览器显示的是字符串,而不是该标签。 #如果不标记,在html里面把{{ temp }}修改为{{ temp|safe }} def test(request): from django.utils.safestring import mark_safe temp = '<a href="http://www.baidu.com">百度</a>' temp = mark_safe(temp) return render(request,'test.html',{'temp':temp})
    form.html
    
    <body>
    
    <form method="POST" action="/content/">
        <p>评论:
            <input type="text" name="content">
        </p>
        <p>
            <input type="submit" value="提交">
            <span style="color:red;">{{ error }}</span>
        </p>
    </form>
    
    </body>
    comment.html
    
    <body>
    
    <h1>评论</h1>
    {% for i in lis %}
        <div>{{ i|safe }}</div>
    {% endfor %}
    
    </body>
    test.html
    
    
    <body>
    
    {{ temp }}
    
    </body>
    urls.py
    
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('content/', views.content),
        path('comment/', views.comment),
        path('test/', views.test),
    ]
  • 相关阅读:
    overflow+文档流
    《大器晚成》读后感 读书笔记
    《指标陷阱》读后感 读书笔记
    《无限的游戏》读后感 读书笔记
    《最蓝的眼睛》读后感 读书笔记
    《正常人》读后感 读书笔记
    《玉米人》读后感 读书笔记
    《科举史》读后感 读书笔记
    《糖的故事》读后感 读书笔记
    《蒙克传》读后感 读书笔记
  • 原文地址:https://www.cnblogs.com/python-daxiong/p/12773834.html
Copyright © 2011-2022 走看看