Django筆記08

Django中間件html

  中間件相似於django的門衛,數據在進入和離開時都須要通過中間件ajax

  能作全局訪問的頻率限制,身份校驗,黑名單,白名單等全局的限制django

  用法:新建一個文件夾,文件夾中新建一個py文件後端

       寫的類必須繼承MiddlewareMixinsession

     from django.utils.deprecation import MiddlewareMixinapp

django容許用戶自定義中間件,而且保留給用戶五個能夠自定義的方法
process_request(self,request) 請求來時執行,這時返回一個HttpResponse對象,後續的中間件都不會走,直接同級返回
process_response(self,request,response) 響應返回時執行
process_view(self,request,callback,callback_args,callback_kwargs) 路由匹配成功執行視圖函數以前
process_exception(self,request,exception) 視圖函數報錯執行
process_template_response(self,request,response)

CSRF跨站請求僞造函數

  form表單中加上:{% csrf_token %}網站

  ajax使用csrf校驗:data:{"csrfmiddlewaretoken":$("[name=csrfmiddlewaretoken]").val()}ui

  局部使用與局部禁用csrf加密

  導入 from django.views.decorators.csrf import csrf_exempt,csrf_protect

FBV
局部禁用 @csrf_exempt
def index(request):   pass
局部使用
@csrf_protect
def index(self):
  pass
CBV
from django.utils.decorators import method_decorator
form django.views.decorators.csrf import csrf_exempt,csrf_protect
@method_decorator(csrf_exempt,name="dispatch") 給類加上裝飾器
@method_decorator(csrf_exempt)給dispathch函數加上裝飾器

https://www.cnblogs.com/liuqingzheng/articles/9509739.html

https://www.cnblogs.com/Dominic-Ji/p/9229509.html?tdsourcetag=s_pctim_aiomsg

 

Auth認證模塊

  auth_user 表默認建立

  建立用戶不能手動在表中插入,密碼是加密的

auth認證
  from django.contrib import auth
  user = auth.authenticate(request,username=username,password=password)
login(HttpRequest,user)
  該函數接受一個HttpRequest對象和一個通過認證的User對象
  該函數實現用戶登陸功能,本質上會在後端爲該用戶生成相關session數據
註銷
  auth.logout(reuqest)
  等價於刪除session數據request.session.flush()
裝飾器校驗是否登陸及跳轉
  from django.contrib.auth.decorators import login_required
  @login_required(跳轉地址)
  def my_view(request):
    pass
  能夠在配置文件中指定auth校驗登陸不合法統一跳轉的路徑
  LOGIN_UTL = '/login/' 既能夠局部配置,也能夠全局配置
建立用戶
  from django.contrib.auth.models import User
  User.objects.createuser() 建立普通用戶
  User.objects.creqtesuperuser() 建立超級用戶
判斷是否經過認證
  request.user.is_authenticated()
校驗密碼,修改密碼
  request.user.check_password(password)檢查密碼是否正確
  request.user.set_password(password="xxx") 修改密碼
  reuqest.user.save() 保存設置
User對象屬性
  is_staff:用戶是否擁有網站的管理權限
  is_active:是否容許用戶登陸,設置False,能夠在不刪除用戶的前提下禁止用戶登陸
擴展默認auth_user表
  第一種:新建一張表與auth_user表一對一外鍵關聯
  第二種:
    from django.contrib.auth.models import AbstractUser
    class UserInfo(AbstractUser):
      phone = models.CharField(max_length=32)
    在settings配置文件中指定使用UserInfo表
    AUTH_USER_MODEL = "app01.UserInfo"

https://www.cnblogs.com/liuqingzheng/articles/9628105.html

相關文章
相關標籤/搜索