模拟 admin 组件url设计思路
项目urls 文件中:
from django.contrib import admin from django.urls import path from stark.service.sites import site urlpatterns = [ path('admin/', admin.site.urls), path('stark/', site.urls), ]
1.路径设计格式:列表中放路径
1.第一级路径 :path ("stark/" , ([path1,path2,path3,......] ,None,None) ) 或 path( “stark/”, urls1 ) # urls1 可以是一个函数的返回值,该函数的返回值为元组,元组第一个
元素为一个列表,第二和第三个元素分别为None
@property
def urls(self):
temp=[ ]
for model ,config_obj in self._registry.items():
app_label = model._meta.app_label
model_name =model._meta.model_name
temp.append(
path("%s/%s/".%(app_label,model_name), congfig.urls)
)
return temp, None,None
2.第二级路径 path1 : path (" app_name/model_name" , ([ path1,path2,path3,........] ,None,None) ) 或 path("%s/%s/".%(app_label,model_name), congfig.urls)
config.urls 该函数:
def urls(self):
temp=[
path (" ", self.list_view),
path("add" ,self.add_view),
path("change",self.change_view),
path("delete",self.delete_view)
]
return temp,None,None
二. stark 组件中 sites文件中 urls 的设计 :
from django.urls import path,re_path from django.shortcuts import HttpResponse,render,redirect class ModelStark(): def __init__(self,model): self.model = model def list_view(self,request): model_name = self.model._meta.model_name return render(request,"list_view.html",locals()) def add_view(self,request): return HttpResponse("add_view") def change_view(self,request,id): return HttpResponse("change_view") def delete_view(self,request,id): return HttpResponse("delete_view") def get_urls(self): temp=[ path('', self.list_view), path('add/', self.add_view), re_path('(d+)/change/', self.change_view), re_path('(d+)/delete/', self.delete_view), ] return temp @property def urls(self): return self.get_urls(),None,None class StarkSite(): # 基础类,用于注册 def __init__(self): self._registry={} #用于注册模型类 ,以及配置模型类 def register(self,model,Stark_class=None): Stark_class = Stark_class or ModelStark self._registry[model] = Stark_class(model) def get_urls(self): temp=[] for model,config_obj in self._registry.items(): model_name = model._meta.model_name app_label = model._meta.app_label temp.append( path("%s/%s/"%(app_label,model_name),config_obj.urls) ) # print(temp) return temp @property def urls(self): return self.get_urls(),None,None #实例化一个单例对象 site = StarkSite()