一.什么是session

session是保存在服务端的键值对,Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。

二.FVB中使用装饰器进行session验证

认证装饰器:

# 登陆验证
def auth(func):
'''判断是否登录装饰器'''
def inner(request, *args, **kwargs):
ck = request.session.get("username")
'''如果没有登陆返回到login.html'''
if not ck:
return redirect("/login.html")
return func(request, *args, **kwargs)
return inner

 在需要认证的函数执行前加上装饰器认证即可,实际中应用如下:

def login(request):
if request.method == "GET":
return render(request, "login.html")
else:
username = request.POST.get("user")
pwd = request.POST.get("pwd")
pwd = md5(pwd)
dic = {"flag":False}
obj = User.objects.filter(username=username, pwd=pwd).first()
if obj:
request.session["username"] = username
return redirect("/index.html")
else:
print(dic)
return HttpResponse(json.dumps(dic)) @auth
def index(request):
user = request.session.get("username")
business = Business.objects.all().values("name")
host_list = Host.objects.all().values("id","host","port","business__name")
username = User.objects.all().values("username")
return render(request, 'index.html', {'host_list':host_list,"business":business,"user":user,"username":username}) @auth
def addhost(request):
business = Business.objects.all().values("name")
if request.method == "POST":
user = request.session.get("username")
host = request.POST.get("host")
port = request.POST.get("port")
select_business = request.POST.get("business")
business_id = Business.objects.filter(name=select_business).values("id")[0]
host = Host.objects.create(host=host,
port=port,
business_id=business_id["id"])
# host.business.add(*business)
return render(request, "index.html") return render(request, "index.html", {"business":business}) @auth
def up_business(request):
if request.method == "POST":
user = request.session.get("username")
host= request.POST.get("host")
port= request.POST.get("port")
business_name = request.POST.get("business")
username = request.POST.get("username")
print(host,port,business_name,username)
return render(request,"保存成功")

三.CBV中使用类继承的方式进行session认证

  • cbv是 class based view(基于类)
  • cbv基于dispatch进行反射,get获取,post提交
  • 应用场景:登录认证(继承dispatch,在dispatch里做session验证)

CBV第一种方式继承

1.单继承

扫盲:(继承的时候,一定要清楚self是哪个类实例化出来的对象,下例,self为B实例化的对象,任何属性优先从自己里面找,找不到在去父类里找)

class A(object):
def aaa(self):
print('from A')
def bbb(self):
self.aaa() class B(A):
def aaa(self):
print('from B') c = B()
c.aaa()

应用:

from django.views import View
class BaseView(View):
def dispatch(self, request, *args, **kwargs): # 继承父类的dispatch,因为父类里有返回值,所以也要有return
if request.session.get('username'):
response = super(BaseView, self).dispatch(request, *args, **kwargs)
return response
else:
return redirect('/login.html') class IndexView(BaseView): def get(self, request, *args, **kwargs):
return HttpResponse(request.session['username'])

2.多继承(继承顺序从左到右)

class BaseView(object):
def dispatch(self, request, *args, **kwargs):
if request.session.get('username'):
response = super(BaseView,self).dispatch(request, *args, **kwargs)
return response
else:
return redirect('/login.html') class IndexView(BaseView,View):#先去找BaseView,BaseView中未定义在去找View def get(self,request,*args,**kwargs):
return HttpResponse(request.session['username'])

CBV第二种方式装饰器

from django.utils.decorators import method_decorator

def auth(func): #定义装饰器
def inner(request,*args,**kwargs):
if request.session.get('username'):
obj = func(request,*args,**kwargs)
return obj
else:
return redirect('/login.html')
return inner @method_decorator(auth,name='get') #放在类顶部就需要method_decorator这个装饰器
class IndexView(View): @method_decorator(auth) #放在dispatch上就相当于全局都需要经过认证
def dispatch(self, request, *args, **kwargs):
if request.session.get('username'):
response = super(IndexView,self).dispatch(request, *args, **kwargs)
return response
else:
return redirect('/login.html') @method_decorator(auth)
def get(self,request,*args,**kwargs):
return HttpResponse(request.session['username']) @method_decorator(csrf_exempt) # 无效 csrf 放到post函数上的装饰器,是无效的,需要放到dispath上或者类上
def post(self,request,*args,**kwargs):
return HttpResponse(request.session['username'])

四.中间件middleware

如下是django的生命周期

如下为中间件的执行顺序

- 中间件执行时机:请求到来,请求返回时
  - 中间件是一个类:
  def process_request(self,request):
    print('m2.process_request')

  def process_response(self,request, response):
    print('m2.prcess_response')
    return response

    - 应用:
    - 请求日志
    - 用户登录认证

Django根目录新建md文件夹,新建Middleware.py文件

from django.utils.deprecation import MiddlewareMixin

class M1(MiddlewareMixin):
'''先执行request,然后到url路由,url之后返回到最上方,在执行view,如果出现错误就直接到response上,执行完,到真正到视图,如果有问题就
执行exception,从下至上查找,如果找到exception就直接执行exception的return在走response返回用户
每个中间件中,4个方法不需要都写.
'''
def process_request(self,request): if request.path_info == "/login.html":
return None
user_info = request.session.get("username")
if not user_info:
return redirect("/login.html")

注:新的django版本可能不存在MiddlewareMixin,需要手动写一下这个类进行继承

class MiddlewareMixin(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__() def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response class M1(MiddlewareMixin): def process_request(self,request): if request.path_info == "/login.html":
return None
user_info = request.session.get("username")
if not user_info:
return redirect("/login.html")

settings里配置:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'md.Middleware.M1',
] WSGI_APPLICATION = 'BBS.wsgi.application' SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认) SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = True # 是否每次请求都保存Session,默认修改之后才保存(默认)

Django之session验证的三种姿势的更多相关文章

  1. django之创建第7-6-第三种传值方式

    1.创建bar.html文件 <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  2. 设置session超时的三种方式

    设置session超时的三种方式 1. 在容器中设置:如在tomcat-7\conf\web.xml中设置 Tomcat默认session超时时间为30分钟,可以根据需要修改,负数或0为不限制sess ...

  3. 一级缓存、二级缓存、延迟加载、hibernate session 域 pojo三种状态

    1.一级缓存(session缓存 ).二级缓存      意义:提高hibernate查询效率.    缺点:可能会因并发,产生数据不一致.      本质:基于session 的缓存,利用hiber ...

  4. 让Session失效的三种方法

    我们设置SESSION失效的时间,是为了确保在用户长时间不与服务器交互的情况下,可以自动退出登录.本文介绍了三种设置SESSION失效的方法,希望对你有帮助. Session对象是HttpSessio ...

  5. Django多对多表的三种创建方式,MTV与MVC概念

    MTV与MVC MTV模型(django): M:模型层(models.py) T:templates V:views MVC模型: M:模型层(models.py) V:视图层(views.py) ...

  6. 关于 tomcat 集群中 session 共享的三种方法

    前两种均需要使用 memcached 或redis 存储 session ,最后一种使用 terracotta 服务器共享. 建议使用 redis,不仅仅因为它可以将缓存的内容持久化,还因为它支持的单 ...

  7. Tomcat 集群中 实现session 共享的三种方法

    前两种均需要使用 memcached 或 redis 存储 session ,最后一种使用 terracotta 服务器共享. 建议使用 redis ,不仅仅因为它可以将缓存的内容持久化,还因为它支持 ...

  8. Django 多对多表的三种创建方式

    第一种: class Book(models.Model): name = models.CharField(max_length=32) # 第一种自动创建 authors = models.Man ...

  9. ASP.NET中身份验证的三种方法

    Asp.net的身份验证有有三种,分别是"Windows | Forms | Passport",其中又以Forms验证用的最多,也最灵活.Forms 验证方式对基于用户的验证授权 ...

随机推荐

  1. C#问题记录-CallbackOnCollectedDelegate

    做项目的时候遇到了这个问题: 检测到:CallbackOnCollectedDelegate 对“xx.HookProc::Invoke”类型的已垃圾回收委托进行了回调.这可能会导致应用程序崩溃.损坏 ...

  2. 多进程——waitpid()函数的小例子

    本例中使用fork()创建一个子进程,然后让子进程暂停5s,接下来对原有的父进程使用waitpid()函数,利用WNOHANG使父进程不会阻塞每隔一秒判断子进程是否退出. #include" ...

  3. 【挖坑】2019年JAVA安全总结:SQL注入——新项目的开发与老项目的修复

    如何在项目中有效的防止SQL注入 写给需要的人,所有的问题源自我们的不重视. 本章略过"什么是SQL注入","如何去利用SQL注入"的讲解,仅讲如何去防御 PS ...

  4. hdu1213-How Many Tables---基础并查集

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1213 题目大意: 今天是Ignatius的生日,他邀请了许多朋友.现在是吃晚饭的时间,Ignatiu ...

  5. Wired Memory

    https://developer.apple.com/library/content/documentation/Performance/Conceptual/ManagingMemory/Arti ...

  6. 浅谈KD-Tree

    前言 \(KD-Tree\)是一个十分神奇的东西,其实本质上类似于一个\(K\)维的二叉搜索树. 核心思想 \(KD-Tree\)的核心思想与\(BST\)是差不多的(插入等操作也都基本上一样). 唯 ...

  7. mongodb索引 全文索引

    全文索引,也叫文本索引,平时,我们百度的搜索,比如api文档的搜索,这种全局的索引就可以使用全文索引实现 全文索引:对字符串与字符串数组创建全文可搜索对索引 使用情况:比如有一个数据集合,存储了用户的 ...

  8. python剑指offer 合并两个排序的链表

    题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. # -*- coding:utf-8 -*- # class ListNode: # def _ ...

  9. linux分区之ext2,ext3,ext4,gpt

    linux分区之ext2,ext3,ext4,gpt 2013-07-10 12:00:24 标签:ext3 gpt 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明 ...

  10. Vue之Vue-touch的使用

    最近项目中,有的页面发现设置返回键看起来怪怪的,感觉与整体不协调,于是就考虑使用手势滑动事件来实现返回功能~ 开叉查阅资料~找到了vue-touch,使用起来可谓是简单粗暴啊,适合我这样的快速开发人员 ...