django之防止csrf跨站***

環境同前django文章。


啓動dajngo的web服務:

]# cd py3/django-test1/test4
]# python manage.py runserver 192.168.255.70:8000


定義2個視圖,其中csrf1提交表單,csrf2接收提交的表單:

]# vim bookshop/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import *

#csrf
def csrf1(request):
    return render(request, 'bookshop/csrf1.html')
def csrf2(request):
    uname = request.POST['usernmae']
    return HttpResponse(uname)

#查詢一個值
#def index(request):
#    hero = HeroInfo.objects.get(pk=1) #查詢主鍵(pk)=1的條目
#    context = {'hero':hero}
#    return render(request,'bookshop/index.html',context)


#查詢多個值,在html模板中循環
def index(request):
    #list = HeroInfo.objects.all()
    list = HeroInfo.objects.filter(isDelete=False)
    context = {'list1':list}
    return render(request,'bookshop/index.html',context)
def show(request,id):
    context = {'id':id}
    return render(request,'bookshop/show.html',context)
#模板繼承
def index2(request):
    return render(request,'bookshop/index2.html')
def user1(request):
    context = {'username':'python-django'}
    return render(request, 'bookshop/user1.html', context)
def user2(request):
    return render(request, 'bookshop/user2.html')
#html轉義
def htmlTest(request):
    context = {'key1':'<h1>html 轉義</h1>'}
    return render(request, 'bookshop/htmlTest.html',context)

定義html模板:

]# vim templates/bookshop/csrf1.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="csrf2" method="post">
  <input type="text" name="username">
  <input type="submit" value="提交">
</form>
</body>
</html>

添加應用url路由:

]# vim bookshop/urls.py
from django.conf.urls import url
from .  import views
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(\d+)$', views.show, name='show'),
    url(r'^(\d+)/(\d+)$', views.show, name='show'),
    url(r'^index2$', views.index2, name='index2'),
    url(r'^user1', views.user1, name='user1'),
    url(r'^user2', views.user2, name='user2'),
    url(r'^htmlTest',views.htmlTest),
    url(r'^csrf1$',views.csrf1),
    url(r'^csrf2$',views.csrf2),
]

訪問瀏覽器:http://192.168.255.70:8000/csrf1

QQ截圖20181216001425.png

輸入一個單詞,點擊提交,此時,沒有在html模板文件中使用csrf開啓功能,會顯示403:

QQ截圖20181216001557.png


下面在html模板文件中, templates/bookshop/csrf1.html添加防csrf跨站***:即在form標籤之間添加{%csrf_token%}

]# cat templates/bookshop/csrf1.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="csrf2" method="post">
  {% csrf_token %} 
  <input type="text" name="username">
  <input type="submit" value="提交">
</form>
</body>
</html>

使用shift+F5,強制刷新後,再次訪問:http://192.168.255.70:8000/csrf1

輸入單詞,提交:

QQ截圖20181216001942.png

可以正常顯示了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章