Django基础五之中间件

 

具体代码.参照项目diango022多表图书

1.在项目中新建一个文件夹.命名为middleware.放进app01中,并新建一个py.命名为middleware.py

image-20200731152913422

 

2.在middleware.py中写中间件.包含中间件请求时.用session.这样就不用装饰器。

# _*_ coding : UTF-8 _*_
#开发团队:zeng
#开发人员:
#开发时间:2020/7/31 11:06
#文件名称:middleware.py
#开发工具:PyCharm

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,redirect
from django.urls import reverse
class M1(MiddlewareMixin):

   # 白名单
   write_list = [reverse('login')]
   def process_request(self,request):

       print('请求来了')
       path = request.path
       print(path)
       if path not in self.write_list:
           status = request.session.get('is_login')
           print(status)
           if not status:
               return redirect('/login/')


# 第二种
#     def process_request(self, request):
#         write_list = [reverse('login')]
#         print('请求来了')
#         path = request.path
#         print(path)
#         if path in write_list:
#             self.__count = 0
#             return None
#         else:
#
#             status = request.session.get('is_login')
#             print(status)
#             if status:
#                 return None
#             else:
#                 return redirect(reverse('login'))

   def process_response(self,request,response):
       print('响应要走了')
       return response

 

3.在settings.py中把中间件注册

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',
   'app01.middleware.middleware.M1',
]

 

4.在views.py视图中.写了有多个cookis和session..包括是否有装饰器.

from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.

# def wapper(f):
#
#     def inner(request,*args,**kwargs):
#         print(request.COOKIES)
#         is_login = request.COOKIES.get('is_login')
#         if is_login == 'True':
#             ret = f(request,*args,**kwargs)
#             return ret
#
#         else:
#             return redirect('login')
#
#     return inner

#
# # @wapper
# def books(request):
#     if request.method == 'GET':
#         book_obj = models.Book.objects.all()
#         return render(request,'books.html',{'book_obj':book_obj})
#
# # @wapper
# def add_book(request):
#     if request.method == 'GET':
#         publish_all = models.Publish.objects.all()
#         author_all = models.Author.objects.all()
#         return render(request,'add_book.html',{'publish_all':publish_all,'author_all':author_all})
#
#     else:
#         print(request.POST)
#         authons_obj = request.POST.getlist('authors')
#         # print(authons_obj)
#
#         data_obj = request.POST.dict()
#         del data_obj['csrfmiddlewaretoken']
#         del data_obj['authors']
#
#         new_data_obj = models.Book.objects.create(
#             **data_obj
#         )
#         new_data_obj.authors.add(*authons_obj)
#
#         return redirect('books')
#
#
# # @wapper
# def edit_book(request,book_id):
#     book_obj = models.Book.objects.filter(pk=book_id)
#     if request.method == 'GET':
#         book_obj = book_obj.first()
#         publish_obj = models.Publish.objects.all()
#         authors_obj = models.Author.objects.all()
#
#         return render(request,'edit_book.html',{'book_obj':book_obj,'publish_obj':publish_obj,'authors_obj':authors_obj})
#
#     else:
#         print(request.POST)
#         author_obj = request.POST.getlist('authors')
#         data_obj = request.POST.dict()
#         del data_obj['csrfmiddlewaretoken']
#         del data_obj['authors']
#         book_obj.update(
#             **data_obj
#         )
#         book_obj.first().authors.set(author_obj)
#
#         return redirect('books')
#
# # @wapper
# def del_book(request,book_id):
#     models.Book.objects.filter(pk=book_id).delete()
#     return redirect('books')
#
#
# # cookie
#
#
# # def login(request):
# #     if request.method =='GET':
# #         return render(request,'login.html')
# #
# #     else:
# #         # print(request.POST)
# #         username = request.POST.get('username')
# #         pwd = request.POST.get('password')
# #
# #         if username =='123' and pwd == '123':
# #             print('ok')
# #             ret = redirect('books')
# #             ret.set_cookie('is_login',True,10) #100秒是超过后失效
# #             return ret
# #         else:
# #
# #
# #             return redirect('login')

#=================================================================================================================
# session 模式
# 用于用户检验,短信验证过期,权限管理

# session 模式的装饰器
# def wapper(f):
#
#     def inner(request,*args,**kwargs):
#         print(request.session)
#         # is_login = request.COOKIES.get('is_login')
#         is_login = request.session.get('is_login')
#         if is_login == True:
#             ret = f(request,*args,**kwargs)
#             return ret
#
#         else:
#             return redirect('login')
#
#     return inner
#
#
#
#
# def login(request):
#     if request.method =='GET':
#         return render(request,'login.html')
#
#     else:
#         # print(request.POST)
#         username = request.POST.get('username')
#         pwd = request.POST.get('password')
#
#         if username =='123' and pwd == '123':
#
#             # ret = redirect('books')
#             # ret.set_cookie('is_login',True,10) #100秒是超过后失效
#             request.session['is_login'] = True
#             request.session.set_expiry(1000) #设置时间.如整数的话.是秒.如时间的话
#             '''
#     * 如果value是个整数,session会在些秒数后失效。
#     * 如果value是个datatime或timedelta,session就会在这个时间后失效。
#     * 如果value是0,用户关闭浏览器session就会失效。
#     * 如果value是None,session会依赖全局session失效策略。
#
#             '''
#             # request.session['user']
#
#             return redirect('books')
#         else:
#
#
#             return redirect('login')
#
# # 用装饰器
# @wapper
# def books(request):
#
#     if request.method == 'GET':
#         book_obj = models.Book.objects.all()
#         return render(request,'books.html',{'book_obj':book_obj})
#
# @wapper
# def add_book(request):
#
#     if request.method == 'GET':
#         publish_all = models.Publish.objects.all()
#         author_all = models.Author.objects.all()
#         return render(request,'add_book.html',{'publish_all':publish_all,'author_all':author_all})
#
#     else:
#         print(request.POST)
#         authons_obj = request.POST.getlist('authors')
#         # print(authons_obj)
#
#         data_obj = request.POST.dict()
#         del data_obj['csrfmiddlewaretoken']
#         del data_obj['authors']
#
#         new_data_obj = models.Book.objects.create(
#             **data_obj
#         )
#         new_data_obj.authors.add(*authons_obj)
#
#         return redirect('books')
#
# @wapper
# def edit_book(request,book_id):
#
#     book_obj = models.Book.objects.filter(pk=book_id)
#     if request.method == 'GET':
#         book_obj = book_obj.first()
#         publish_obj = models.Publish.objects.all()
#         authors_obj = models.Author.objects.all()
#
#         return render(request,'edit_book.html',{'book_obj':book_obj,'publish_obj':publish_obj,'authors_obj':authors_obj})
#
#     else:
#         print(request.POST)
#         author_obj = request.POST.getlist('authors')
#         data_obj = request.POST.dict()
#         del data_obj['csrfmiddlewaretoken']
#         del data_obj['authors']
#         book_obj.update(
#             **data_obj
#         )
#         book_obj.first().authors.set(author_obj)
#
#         return redirect('books')
#
# @wapper
# def del_book(request,book_id):
#
#     models.Book.objects.filter(pk=book_id).delete()
#     return redirect('books')


# 以下是不用装饰器
# =============================================================================
# def books(request):
#     is_login = request.session.get('is_login')
#     if is_login== True:
#
#         if request.method == 'GET':
#             book_obj = models.Book.objects.all()
#             return render(request,'books.html',{'book_obj':book_obj})
#
#     else:
#         return redirect('login')




# def add_book(request):
#     is_login = request.session.get('is_login')
#     if is_login == True:
#         if request.method == 'GET':
#             publish_all = models.Publish.objects.all()
#             author_all = models.Author.objects.all()
#             return render(request,'add_book.html',{'publish_all':publish_all,'author_all':author_all})
#
#         else:
#             print(request.POST)
#             authons_obj = request.POST.getlist('authors')
#             # print(authons_obj)
#
#             data_obj = request.POST.dict()
#             del data_obj['csrfmiddlewaretoken']
#             del data_obj['authors']
#
#             new_data_obj = models.Book.objects.create(
#                 **data_obj
#             )
#             new_data_obj.authors.add(*authons_obj)
#
#             return redirect('books')
#     else:
#         return redirect('login')



# def edit_book(request,book_id):
#     is_login = request.session.get('is_login')
#     if is_login == True:
#         book_obj = models.Book.objects.filter(pk=book_id)
#         if request.method == 'GET':
#             book_obj = book_obj.first()
#             publish_obj = models.Publish.objects.all()
#             authors_obj = models.Author.objects.all()
#
#             return render(request,'edit_book.html',{'book_obj':book_obj,'publish_obj':publish_obj,'authors_obj':authors_obj})
#
#         else:
#             print(request.POST)
#             author_obj = request.POST.getlist('authors')
#             data_obj = request.POST.dict()
#             del data_obj['csrfmiddlewaretoken']
#             del data_obj['authors']
#             book_obj.update(
#                 **data_obj
#             )
#             book_obj.first().authors.set(author_obj)
#
#             return redirect('books')
#     else:
#         return redirect('login')



# def del_book(request,book_id):
#     is_login = request.session.get('is_login')
#     if is_login == True:
#
#         models.Book.objects.filter(pk=book_id).delete()
#         return redirect('books')
#     else:
#         return redirect('login')


def logout(request):
   request.session.flush()
   return redirect('login')

#================================================================================
# 第三种..用中间件来session.就不需要写装饰器了.

def login(request):
   if request.method == 'GET':
       return render(request, 'login.html')

   else:
       # print(request.POST)
       username = request.POST.get('username')
       pwd = request.POST.get('password')

       if username == '123' and pwd == '123':

           # ret = redirect('books')
           # ret.set_cookie('is_login',True,10) #100秒是超过后失效
           request.session['is_login'] = True
           request.session.set_expiry(1000)  # 设置时间.如整数的话.是秒.如时间的话
           '''
  * 如果value是个整数,session会在些秒数后失效。
  * 如果value是个datatime或timedelta,session就会在这个时间后失效。
  * 如果value是0,用户关闭浏览器session就会失效。
  * 如果value是None,session会依赖全局session失效策略。

          '''
           # request.session['user']

           return redirect('books')
       else:

           return redirect('login')




def books(request):
   if request.method == 'GET':
       print('book函数')
       book_obj = models.Book.objects.all()
       return render(request,'books.html',{'book_obj':book_obj})


def add_book(request):
   if request.method == 'GET':
       print('add_book函数')
       publish_all = models.Publish.objects.all()
       author_all = models.Author.objects.all()
       return render(request,'add_book.html',{'publish_all':publish_all,'author_all':author_all})

   else:
       print(request.POST)
       authons_obj = request.POST.getlist('authors')
       # print(authons_obj)

       data_obj = request.POST.dict()
       del data_obj['csrfmiddlewaretoken']
       del data_obj['authors']

       new_data_obj = models.Book.objects.create(
           **data_obj
      )
       new_data_obj.authors.add(*authons_obj)

       return redirect('books')



def edit_book(request,book_id):
   book_obj = models.Book.objects.filter(pk=book_id)
   if request.method == 'GET':
       print('edit_book函数')
       book_obj = book_obj.first()
       publish_obj = models.Publish.objects.all()
       authors_obj = models.Author.objects.all()

       return render(request,'edit_book.html',{'book_obj':book_obj,'publish_obj':publish_obj,'authors_obj':authors_obj})

   else:
       print(request.POST)
       author_obj = request.POST.getlist('authors')
       data_obj = request.POST.dict()
       del data_obj['csrfmiddlewaretoken']
       del data_obj['authors']
       book_obj.update(
           **data_obj
      )
       book_obj.first().authors.set(author_obj)

       return redirect('books')

def del_book(request,book_id):
   models.Book.objects.filter(pk=book_id).delete()
   return redirect('books')

 

posted @ 2020-07-31 15:40  水晶冰洛  阅读(319)  评论(0编辑  收藏  举报