一、引子
http协议是无状态的,就是它不会记录请求和响应的任何信息,比如你访问一个服务器的一个网页时,先要你登录一下,然后进入网页,但当你要进入这个服务器的另一个网页时,它照常不会知道刚才你已经登录过了,又要让你登录一下,就是一个bug。但是,你说你每次上网的时候,只需要登录一下就行了,并没有我说的让你每次都登录,这是会话路径技术帮你记录了你的登录信息,现在我们们就来讲讲django的会话路径技术cookie和session,实现会话追踪。
二、cookie
cookie是key-value结构,类似于一个字典。随着服务器的响应发送给客户端浏览器,然后客户端浏览器会把cookie保存起来,当下一次再访问服务器时把cookie再发送给服务器。
语法:
1
2
|
response.set_cookie() #这是设置cookie值
request.cookies #取cookie值
|
基于cookie的登录页面和主页面
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
|
def login(request): #登录视图
if request.method = = "get" :
return render(request, "login.html" )
else :
user = request.post.get( "user" )
pwd = request.post.get( "pwd" )
user_obj = userinfo.objects. filter (name = user,pwd = pwd).first()
if user_obj: 用户验证成功后,设置cookie值,响应给浏览器,浏览器会保存cookie
# obj=httpresponse("登录成功!")
obj = redirect( "/index/" )
obj.set_cookie( "is_login" ,true, 20 )
obj.set_cookie( "username" ,user)
return obj
return httpresponse( "error!" )
def index(request): #进入主页面视图
print ( "request.cookies" ,request.cookies)
is_login = request.cookies.get( "is_login" ) #首先取到cookie值,对值进行判断
username = request.cookies.get( "username" )
if not is_login: # 值为空时,执行这里,说明之前没有登录过,重定向到登录页面
return redirect( "/login/" )
return render(request, "index.html" ,{ "username" :username})
|
三、session
上面的cookie是浏览器端保存的,现在的session是基于cookie的,但是保存在服务器端的技术,服务器在运行时可以为每一个访问的浏览器设置一个session,然后保存在django下的django_session表中。
语法:
1
2
3
|
request.session[ "k1" ] = "v1" 设置session值
request.session.get( "k1" ) 取session值
request.session.flush() 清空session值
|
基于session的登录页面和主页面的访问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
def login(request):
if request.method = = "get" :
return render(request, "login.html" )
else :
user = request.post.get( "user" )
pwd = request.post.get( "pwd" )
user_obj = userinfo.objects. filter (name = user,pwd = pwd).first()
if user_obj:
request.session[ "is_login" ] = true
request.session[ "username" ] = user
return redirect( "/index/" )
return httpresponse( "error!" ) def index(request):
is_login = request.session.get( "is_login" )
username = request.session.get( "username" ) if not is_login:
return redirect( "/login/" )
return render(request, "index.html" ,{ "username" :username})
|
四、图片验证码的实现
html文件:登录页面
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<!doctype html>
<html lang = "en" >
<head>
<meta charset = "utf-8" >
<title>title< / title>
<link rel = "stylesheet" href = "/static/css/bootstrap.css" rel = "external nofollow" >
<script src = "/static/jquery-3.3.1.js" >< / script>
<script src = "/static/js/bootstrap.js" >< / script>
< / head>
<body>
{ % csrf_token % }
<div class = "container" >
<div class = "row" >
<div class = "col-md-5" >
<div style = "color: blue;font-size: 20px" >登录页面< / div>
<div class = "form-group" >
名字 < input type = "text" name = "user" class = "form-control" >
< / div>
<div class = "form-group" >
密码 < input type = "password" name = "pwd" class = "form-control" >
< / div>
<div class = "row form-group" >
<div class = "col-md-6" >验证码< input type = "text" name = "yan" class = "form-control" >< / div>
<div class = "col-md-6" style = "line-height:60px" ><img src = "/img_drow/" alt = " " width=" 200 " height=" 40 ">< / div>
< / div>
<button class = "login" >登录< / button>
<p style = "color: red;font-size: 30px" >< / p>
< / div>
< / div>
< / div>
<script>
$( '.login' ).click(function () {
var name = $( '[name="user"]' ).val();
var pw = $( '[name="pwd"]' ).val();
var yan = $( '[name="yan"]' ).val();
$.ajax({
url: '/login/' ,
type : 'post' ,
data: {csrfmiddlewaretoken: $( '[name="csrfmiddlewaretoken"]' ).val(), user: name, pwd: pw, yan: yan},
success: function (data) {
if (data = = '200' ) {
location.href = '/books/'
}
else if (data = = '100' ) {
$( 'p' ).html( '用户名或密码输入错误' )
}
else {
$( 'p' ).html( '验证码错误' );
var num = math.random();
$( 'img' ).attr( 'src' , '/img_drow?' + num)
}
}
})
});
$( 'img' ).click(function () {
var num = math.random();
$(this).attr( 'src' , '/img_drow?' + num)
})
< / script>
< / body>
< / html>
|
views:
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
产生随机图片验证的视图函数
import random
from pil import image,imagedraw,imagefont
from io import bytesio
def get_random_color():
return random.randint( 0 , 255 ),random.randint( 0 , 255 ),random.randint( 0 , 255 )
def img_drow(request):
img = image.new( 'rgb' ,( 200 , 40 ),get_random_color())
draw = imagedraw.draw(img)
font = imagefont.truetype( 'static/fonts/kumo.ttf' , 34 )
keep_str = ''
for i in range ( 5 ):
num = str (random.randint( 0 , 9 ))
lower = chr (random.randint( 65 , 90 ))
upper = chr (random.randint( 97 , 122 ))
random_char = random.choice([num,lower,upper])
draw.text((i * 30 + 50 , 0 ),random_char,get_random_color(),font = font)
keep_str + = random_char
width = 200
height = 40
for i in range ( 10 ):
x1 = random.randint( 0 ,width)
x2 = random.randint( 0 ,width)
y1 = random.randint( 0 ,height)
y2 = random.randint( 0 ,height)
draw.line((x1,y1,x2,y2),fill = get_random_color())
for i in range ( 10 ):
draw.point([random.randint( 0 , width), random.randint( 0 , height)], fill = get_random_color())
x = random.randint( 0 , width)
y = random.randint( 0 , height)
draw.arc((x, y, x + 4 , y + 4 ), 0 , 90 , fill = get_random_color())
request.session[ 'keep_str' ] = keep_str
f = bytesio()
img.save(f, 'png' )
data = f.getvalue()
return httpresponse(data)
def login(request):
if request.method = = 'get' :
return render(request, 'login.html' )
else :
yan = request.post.get( 'yan' )
if yan.upper() = = request.session.get( 'keep_str' ).upper():
user = request.post.get( 'user' )
pwd = request.post.get( 'pwd' )
obj = userinfo.objects. filter (name = user,pwd = pwd).first()
if obj :
request.session[ 'state' ] = true
request.session[ 'user' ] = user
return httpresponse( '200' )
else :
return httpresponse( '100' )
else :
return httpresponse( '300' )
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/12345huangchun/p/10246930.html