1. 程式人生 > 實用技巧 >Django基礎五之中介軟體

Django基礎五之中介軟體

具體程式碼.參照專案diango022多表圖書

1.在專案中新建一個資料夾.命名為middleware.放進app01中,並新建一個py.命名為middleware.py

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')