Django视图——Cookie&Session

Cookie机制:Cookie分发通过扩展HTTP协议来实现的,服务器通过在HTTP的响应头中加上一行特殊的指示来提示浏览器按照指示成相应的Cookie。然而纯粹的客户端脚本入JavaScript或者VBScript也可以生成Cookie。而Cookie的使用则是由浏览器按照一定的原则在后台自动发送给服务器。浏览器检查所有存储的Cookie,如果某个Cookie所声明的作用范围大于等于将要请求的资源所在的位置,则把该Cookie附在请求资源HTTP请求头上发送给服务器。

Session机制:Session机制是一种服务器端的机制,服务器使用一种类似于散列表的结构来保存信息。

1.Cookie的使用

修改views.py文件。

def login_action(request):
    if request.method == "POST":
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        if username == "admin" and password == "admin123":
            # return HttpResponse("Login Success!!!")
            # return render(request,"login_success.html")
            # redirect——重定向
            response = HttpResponseRedirect('/login_success/')
            # 设置浏览器cookie
            response.set_cookie('user', username, 3600)
            return response
        else:
            return render(request, "index.html", {'error': 'username or password error!'})


def login_success(request):
    # 读取浏览器cookie
    username = request.COOKIES.get('user', '')
    return render(request, "login_success.html", {"user": username})

当用户登录成功后,在跳转到login_success视图函数的过程中,通过set_cookie()方法向浏览器中添加Cookie信息。

这里给set_cookie()方法传了三个参数:第一个参数"user"用于表示写入浏览器的Cookie名,第二个参数username是由用户在登录页上输入的用户名(即"admin"),第三个参数3600用于设置Cookie信息在浏览器中的保持时间,默认单位为秒。

在login_success视图函数中,通过request.COOKIES来读取Cookie名为"user"的值。并且通过render将它和login_success.html页面一起返回。

修改login_success.html页面,添加<div>标签来显示用户名。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login Success Page</title>
</head>
<body>
<h1>Congratulations on homepage!!!</h1>
<div style="float: right;"><!--float定义位置,hr下划线-->
    <a>嘿!{{ user }} 欢迎</a>
    <hr/>
</div>
</body>
</html>

这边说一个也是刚刚学到的一个小知识点,就是之前使用eclipse,可以设置联想功能(通俗的说就是,不管你打什么,IDE都会把这些开头的方法联想给你选择)。在使用pycharm时,你打小写字母关联不出大写字母开头的方法,用起来不方便,特意找了一下,分享给大家

2.Session的使用

修改views.py文件。

def login_action(request):
    if request.method == "POST":
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        if username == "admin" and password == "admin123":
            # return HttpResponse("Login Success!!!")
            # return render(request,"login_success.html")
            # redirect——重定向
            response = HttpResponseRedirect('/login_success/')
            # 设置浏览器cookie
            # response.set_cookie('cookie_user', username, 3600)
            # 将session信息记录到浏览器
            request.session['session_user'] = username
            return response
        else:
            return render(request, "index.html", {'error': 'username or password error!'})


def login_success(request):
    # 读取浏览器cookie
    # username = request.COOKIES.get('cookie_user', '')
    username=request.session.get('session_user','')
    return render(request, "login_success.html", {"session_user": username})

session机制需要从Web服务器来记录用户的信息,那么一定要有存放用户sessionid对应信息的地方才行。所以,我们需要创建django_session表。django默认有这些常用的表,只需将它们生成即可。

指令为:python manage.py migrate

3.django认证系统

(venv) D:\python\yupengcheng\djangodemo>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

使用"migrate"命令进行数据迁移时,该表中存放的用户信息可以用来登录django自带的Admin管理后台。在此之前先来创建登录Admin后台的管理员账号。

创建超级管理员账号/密码:admin/admin123

Admin管理后台登录地址:http://127.0.0.1:8000/admin/

(venv) D:\python\yupengcheng\djangodemo>python manage.py createsuperuser
Username (leave blank to use 'yupengcheng'): admin
Email address: [email protected]
Password:
Password (again):
The password is too similar to the email address.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
def login_action(request):
    if request.method == "POST":
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            request.session['user'] = username
            response = HttpResponseRedirect('/login_success/')
            return response
        else:
            return render(request, "index.html", {'error': 'username or password error!'})

使用authenticate()函数认证给出的用户名和密码。它接受两个参数:username和password,并且会在用户名密码正确的情况下返回一个user对象,否则authenticate()返回None。

通过if语句判断authenticate()返回对象,如果不为None,则说明用户认证通过,调用login()函数进行登录。login()函数接收HttpRequest对象和一个user对象。

使用前面超级管理员账号(admin/admin123),或者通过Admin管理后台创建用户账号来验证登录功能。

 

print_r('点个赞吧');
var_dump('点个赞吧');
NSLog(@"点个赞吧!")
System.out.println("点个赞吧!");
console.log("点个赞吧!");
print("点个赞吧!");
printf("点个赞吧!\n");
cout << "点个赞吧!" << endl;
Console.WriteLine("点个赞吧!");
fmt.Println("点个赞吧!")
Response.Write("点个赞吧");
alert(’点个赞吧’)

猜你喜欢

转载自blog.csdn.net/qq_41470573/article/details/85232224