标签:item pes 运行 ast war pychar web资源 数据库迁移 title
会话是指一个终端用户(服务器)与交互系统(客户端)进行通讯的过程。
对同一个用户对服务器的连续的请求和接受响应的监视。(将用户与同一用户发出的不同请求之间关联,为了数据共享)
浏览器与服务器之间的通信是通过HTTP协议进行通信的,而HTTP协议是”无状态”的协议,它不能保存客户的信息,即一次响应完成之后连接就断开了,下一次的请求需要重新连接,这样就需要判断是否是同一个用户,所以才应会话跟踪技术来实现这种要求
在一个会话的多个请求中共享数据,这就是会话跟踪技术。例如在一个会话中的请求如下: 请求银行主页;
我们知道HTTP协议是无状态协议,也就是说每个请求都是独立的!无法记录前一次请求的状态。但HTTP协议中可以使用Cookie来完成会话跟踪!在Web开发中,使用session来完成会话跟踪,session底层依赖Cookie技术。
Cookie是可以被禁止的。
Cookie是通过HTTP请求和响应头在客户端和服务器端传递的:
如果服务器端发送重复的Cookie那么会覆盖原有的Cookie,例如客户端的第一个请求服务器端发送的Cookie是:Set-Cookie: a=A;第二请求服务器端发送的是:Set-Cookie: a=AA,那么客户端只留下一个Cookie,即:a=AA。
django中的cookie语法
创建一个数据库
mysql> create database cookie_test default charset=utf8;
mysql> use cookie_test;
新建一个项目
root@darren-virtual-machine:~/PycharmProjects# django-admin startproject cookie_seesion
root@darren-virtual-machine:~/PycharmProjects# cd cookie_seesion
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py startapp cookie
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# vim cookie_seesion/settings.py
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘cookie.apps.CookieConfig‘ ]
配置数据库
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘cookie_test‘, ‘HOST‘: ‘127.0.0.1‘, ‘PORT‘: 3306, ‘USER‘: ‘root‘, ‘PASSWORD‘:‘123456‘, } }
只想数据库迁移操作
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py makemigrations
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 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 auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
查看数据库
mysql> show tables;
配置路由分发
from django.contrib import admin from django.urls import path,include urlpatterns = [ path(‘admin/‘, admin.site.urls), path("cookie/",include("cookie.urls")) ]
cookie/urls
from django.urls import path,re_path from cookie import views urlpatterns = [ path("index/",views.index), path("login/",views.login), ]
当url文件把[] 写成{}时,会有如下错误
views视图文件
from django.shortcuts import render,redirect # Create your views here. def index(request): return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": return redirect("/cookie/index/") else: return redirect("/cookie/login/")
模板文件
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# mkdir templates
TEMPLATES = [ { ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [os.path.join(BASE_DIR,"templates")], ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘, ‘django.contrib.messages.context_processors.messages‘, ], }, }, ]
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>index 页面。。。</h3> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>用户登录</h3> <form action="" method="POST"> {% csrf_token %} <p>用户名:<input type="text" name="username"></p> <p>密 码:<input type="password" name="password"></p> <input type="submit"> </form> </body> </html>
访问http://127.0.0.1:8000/cookie/index/
访问http://127.0.0.1:8000/cookie/login并登陆
会得到index页面
但是这样的话,直接访问http://127.0.0.1:8000/cookie/index/也会得到index.html页面
添加一个cookie
from django.shortcuts import render,redirect # Create your views here. def index(request): return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/")
直接访问
登录访问
携带有is_login的cookie
做登陆限制
from django.shortcuts import render,redirect # Create your views here. def index(request): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/")
这样cookie保存在本地,也可以直接访问
cookie注销页面
from django.urls import path,re_path from cookie import views urlpatterns = [ path("index/",views.index), path("login/",views.login), path(‘loginout/‘,views.loginout), ]
views页面
from django.shortcuts import render,redirect # Create your views here. def index(request): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/") def loginout(request): rep = redirect("/cookie/login/") rep.delete_cookie("is_login") return rep
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>index 页面。。。</h3> <a href="/cookie/loginout/">注销</a> </body> </html>
点击注销
再次直接访问index,就不能得到index页面
添加一个订单页面
from django.urls import path,re_path from cookie import views urlpatterns = [ path("index/",views.index), path("login/",views.login), path(‘loginout/‘,views.loginout), path(‘order/‘,views.order), ]
view页面
from django.shortcuts import render,redirect,HttpResponse # Create your views here. def index(request): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/") def loginout(request): rep = redirect("/cookie/login/") rep.delete_cookie("is_login") return rep def order(request): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") return HttpResponse("oreder success")
使用装饰器进行改进
from django.shortcuts import render,redirect,HttpResponse # Create your views here.
#装饰器
def login_required(func): def inner(request,*args,**kwargs): if not request.COOKIES.get("is_login"): return redirect("/cookie/login/") rep = func(request,*args,**kwargs) return rep return inner @login_required def index(request): # if not request.COOKIES.get("is_login"): # return redirect("/cookie/login/") return render(request,"index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": rep = redirect("/cookie/index/") rep.set_cookie("is_login",True) return rep else: return redirect("/cookie/login/") def loginout(request): rep = redirect("/cookie/login/") rep.delete_cookie("is_login") return rep @login_required def order(request): # if not request.COOKIES.get("is_login"): # return redirect("/cookie/login/") return HttpResponse("oreder success")
Session是服务器端技术,利用这个技术,服务器在运行时可以 为每一个用户的浏览器创建一个其独享的session对象,由于 session为用户浏览器独享,所以用户在访问服务器的web资源时 ,可以把各自的数据放在各自的session中,当用户再去访问该服务器中的其它web资源时,其它web资源再从用户各自的session中 取出数据为用户服务。
django初始化数据库的时候,会有一个django_session的表
1.浏览器向服务器发送请求时,第一次的cookie是空的,如果在视图里配置request.session["username"]="joy",则会
生成一个session_key的随机字符串,相当于一把钥匙,
2.会把request的键值对存到session-data里面
3.把随机生成的seesion_key设成一个cookie。seesionid=session_key这样的形式,挡浏览器第二次请求的时候,就会携带这个session_id作为cookie
1、设置Sessions值 request.session[‘session_name‘] ="admin" 2、获取Sessions值 session_name = request.session["session_name"] 3、删除Sessions值 del request.session["session_name"] 4、flush() 删除当前的会话数据并删除会话的Cookie。 这用于确保前面的会话数据不可以再次被用户的浏览器访问 5、get(key, default=None) fav_color = request.session.get(‘fav_color‘, ‘red‘) 6、pop(key) fav_color = request.session.pop(‘fav_color‘) 7、keys() 8、items() 9、setdefault() 10 用户session的随机字符串 request.session.session_key # 将所有Session失效日期小于当前日期的数据删除 request.session.clear_expired() # 检查 用户session的随机字符串 在数据库中是否 request.session.exists("session_key") # 删除当前用户的所有Session数据 request.session.delete("session_key") request.session.set_expiry(value) * 如果value是个整数,session会在些秒数后失效。 * 如果value是个datatime或timedelta,session就会在这个时间后失效。 * 如果value是0,用户关闭浏览器session就会失效。 * 如果value是None,session会依赖全局session失效策略。
创建一个session 的app
root@darren-virtual-machine:~/PycharmProjects/cookie_seesion# python3 manage.py startapp session
注册app
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘cookie.apps.CookieConfig‘, ‘session.apps.SessionConfig‘, ]
urls配置路由分发
from django.contrib import admin from django.urls import path,include urlpatterns = [ path(‘admin/‘, admin.site.urls), path("cookie/",include("cookie.urls")), path("session/",include("session.urls")), ]
url文件
from django.urls import path,re_path from session import views urlpatterns = [ path("index/",views.index), path(‘login/‘,views.login), ]
view文件
from django.shortcuts import render,HttpResponse,redirect # Create your views here. def index(request): if not request.session.get("is_login"):
#1. 从cookie中取出sessionid
#2. 拿到随机字符串到django_session 表中过滤对象
#3. 拿到对象取出data值。 return redirect("/session/login/") return render(request,"session_index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": request.session["is_login"] = True
#1. 生产随机字符串
#2. 将数据存到django_session表中
#3. 设置cookie值。(sessionid,值为随机字符串) return redirect("/session/index/") else: return redirect("/cookie/login/")
访问http://127.0.0.1:8000/session/index,会直接返回http://127.0.0.1:8000/session/login/
登录得到cookie值
查看数据库
mysql> select * from django_session;
默认过期时间是两周
注销登录,清除seedion值
from django.urls import path,re_path from session import views urlpatterns = [ path("index/",views.index), path(‘login/‘,views.login), path(‘logout/‘,views.logout), ]
views文件
from django.shortcuts import render,HttpResponse,redirect # Create your views here. def index(request): if not request.session.get("is_login"): return redirect("/session/login/") return render(request,"session_index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username == "joy" and password == "123456": request.session["is_login"] = True return redirect("/session/index/") else: return redirect("/cookie/login/") def logout(request): request.session.flush() """ 1. 从cookie中取出sessionid 2. 拿到随机字符串到django_session 表中过滤对象 3. 删除该对象。 """ return redirect("/session/login/")
seesiin_index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>session index 页面。。。</h3> <a href="/session/logout">注销</a> </body> </html>
注销后,查看数据库信息,session被清空
查看数据库
实例验证
from django.shortcuts import render,HttpResponse,redirect # Create your views here. def index(request): if not request.session.get("is_login"): return redirect("/session/login/") return render(request,"session_index.html") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST.get("username") password = request.POST.get("password") if username in ["joy","john"] and password == "123456": request.session["is_login"] = True return redirect("/session/index/") else: return redirect("/cookie/login/") def logout(request): request.session.flush() """ 1. 从cookie中取出sessionid 2. 拿到随机字符串到django_session 表中过滤对象 3. 删除该对象。 """ return redirect("/session/login/")
在同一个浏览器,登录joy账号
数据库信息
在同一个浏览器,打开另一个窗口,登录john账号
查看数据库
并没有变化,同样的操作,但是当使用无痕浏览器登录john账号,
结果如下
数据库,不同的浏览器,session不一样
059.Python前端Django组件cooki和session
标签:item pes 运行 ast war pychar web资源 数据库迁移 title
原文地址:https://www.cnblogs.com/zyxnhr/p/12663730.html