Python之路,Day16 - Django 進階


本節內容

自定義template tags

中間件

CRSF

權限管理

分頁

 

 

Django分頁

https://docs.djangoproject.com/en/1.9/topics/pagination/ 

自定義template tags

https://docs.djangoproject.com/es/1.9/howto/custom-template-tags/ 

權限管理

django 自帶有基本的權限管理 ,但粒度和限制權限的維度都只是針對具體的表,如果我們想根據業務功能來限制權限,那就得自己寫了, 不過也不用完全自己的寫,我們可以在django 自帶的權限基礎上輕松的實現擴展。 

自己寫權限要注意:

  1. 權限系統的設計對開發者、用戶要實現透明,即他們不需要改變自己原有的使用系統或調用接口的方式
  2. 權限要易擴展,靈活
  3. 權限要能實現非常小的粒度的控制,甚至細致到一個按鍵某個用戶是否能按。

想對一個功能實現權限控制,要做到只能過在views方法上加一個裝飾器就行了,比如:

@check_permission
@login_required
def customer_detail(request,customer_id):
    customer_obj = models.Customer.objects.get(id=customer_id)
    customer_form = forms.CustomerDetailForm(instance=customer_obj)

    if request.method == 'POST':
        customer_form = forms.CustomerDetailForm(request.POST,instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            parent_base_url = '/'.join(request.path.split('/')[:-2])
            print("url:",parent_base_url )
            return  redirect(parent_base_url)
        else:
            print(customer_form.errors)
    return  render(request,'crm/customer_detail.html',{'customer_form':customer_form})

check_permission的代碼實現

 1 #_*_coding:utf-8_*_
 2 __author__ = 'Alex Li'
 3 from django.core.urlresolvers import resolve
 4 from django.shortcuts import render,redirect
 5 
 6 perm_dic = {
 7     'view_customer_list': ['customer_list','GET',[]],
 8     'view_customer_info': ['customer_detail','GET',[]],
 9     'edit_own_customer_info': ['customer_detail','POST',['test']],
10 }
11 
12 def perm_check(*args,**kwargs):
13     request = args[0]
14     url_resovle_obj = resolve(request.path_info)
15     current_url_namespace = url_resovle_obj.url_name
16     #app_name = url_resovle_obj.app_name #use this name later
17     print("url namespace:",current_url_namespace)
18     matched_flag = False # find matched perm item
19     matched_perm_key = None
20     if current_url_namespace is not None:#if didn't set the url namespace, permission doesn't work
21         print("find perm...")
22         for perm_key in perm_dic:
23             perm_val = perm_dic[perm_key]
24             if len(perm_val) == 3:#otherwise invalid perm data format
25                 url_namespace,request_method,request_args = perm_val
26                 print(url_namespace,current_url_namespace)
27                 if url_namespace == current_url_namespace: #matched the url
28                     if request.method == request_method:#matched request method
29                         if not request_args:#if empty , pass
30                             matched_flag = True
31                             matched_perm_key = perm_key
32                             print('mtched...')
33                             break #no need looking for  other perms
34                         else:
35                             for request_arg in request_args: #might has many args
36                                 request_method_func = getattr(request,request_method) #get or post mostly
37                                 #print("----->>>",request_method_func.get(request_arg))
38                                 if request_method_func.get(request_arg) is not None:
39                                     matched_flag = True # the arg in set in perm item must be provided in request data
40                                 else:
41                                     matched_flag = False
42                                     print("request arg [%s] not matched" % request_arg)
43                                     break #no need go further
44                             if matched_flag == True: # means passed permission check ,no need check others
45                                 print("--passed permission check--")
46                                 matched_perm_key = perm_key
47                                 break
48 
49     else:#permission doesn't work
50         return True
51 
52     if matched_flag == True:
53         #pass permission check
54         perm_str = "crm.%s" %(matched_perm_key)
55         if request.user.has_perm(perm_str):
56             print("\033[42;1m--------passed permission check----\033[0m")
57             return True
58         else:
59             print("\033[41;1m ----- no permission ----\033[0m")
60             print(request.user,perm_str)
61             return False
62     else:
63         print("\033[41;1m ----- no matched permission  ----\033[0m")
64 def check_permission(func):
65 
66     def wrapper(*args,**kwargs):
67         print("---start check perms",args[0])
68         if not perm_check(*args,**kwargs):
69             return render(args[0],'crm/403.html')
70         return func(*args,**kwargs)
71         #print("---done check perms")
72     return wrapper
50行實現細粒度的權限控制

 

  

Middleware中間件 

https://docs.djangoproject.com/es/1.9/topics/http/middleware/#process_request 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM