1.urls.py
"""Django_cookie_session URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path(‘‘, views.home, name=‘home‘) Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path(‘‘, Home.as_view(), name=‘home‘) Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path(‘blog/‘, include(‘blog.urls‘)) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login/‘, views.login), path(‘index/‘, views.index), ]
2.views.py
from django.shortcuts import render, redirect # Create your views here. def login(request): print(‘COOKIES:-->‘, request.COOKIES) print(‘SESSION:-->‘, request.session) if request.method == ‘POST‘: print(‘POST!!!‘) name = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) print(name) print(pwd) if name == ‘ck‘ and pwd == ‘123‘: # ret = redirect(‘/index/‘) # ret.set_cookie(‘user‘, name) # return ret request.session[‘is_login‘] = True request.session[‘user‘] = name return redirect(‘/index/‘) return render(request, ‘login.html‘) def index(request): # if request.COOKIES.get(‘username‘, None): # name = request.COOKIES.get(‘username‘, None) # return render(request, ‘index.html‘, locals()) if request.session[‘is_login‘] == True: name = request.session.get(‘user‘, None) return render(request, ‘index.html‘, locals()) else: return redirect(‘/login/‘)
3.index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ name }}</h1> </body> </html>
4.login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ name }}</h1> </body> </html>
cookies和session是浏览器在访问服务器端口时与连接请求一起发送的内容。
目的是实现用户的登入操作,通过判断用户有没有对应的cookie或是session判断用户登入与否并从中获取用户的个人信息。
cookies与session的区别是session的用户信息是存在服务器端,浏览器提供自己的键,对应的是服务端的键值就是用户的信息。这样保证用户的信息安全。
原文地址:https://www.cnblogs.com/CK85/p/10178562.html
时间: 2024-09-29 09:34:14