零、预备知识 单例对象

  方式一:__new__方法

  方式二:模块导入,只要在引入的文件中实例了这个对象,不管引道哪里,这个对象都指向同一个内存空间

 class My_singleton(object):
     def foo(self):
         print("ok")

 my_singleton = My_singleton()
from xxx import my_singleton
my_singleton.foo()

一、Xadmin之注册与生成url

在Xadmin.apps中:

 from django.apps import AppConfig
 from django.utils.module_loading import autodiscover_modules

 class XadminConfig(AppConfig):
     name = 'Xadmin'

     def ready(self):  #调用这个类时自动执行
         autodiscover_modules('Xadmin')  #从admin.py文件中复制,读取每个app中Xadmin.py文件

在Xadmin.py中:

 from django.conf.urls import re_path
 from django.shortcuts import HttpResponse

 class ModelXadmin(object):
     def __init__(self,model,site):
         self.model = model
         self.site = site

     def list_view(self,request): #查询界面
         return HttpResponse("list_view")
     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")

     @property
     def urls(self):
         temp = []

         temp.append(re_path(r'^$',self.list_view))
         temp.append(re_path(r'^add/$',self.add_view))
         temp.append(re_path(r'^(\d+)/delete/$',self.delete_view))
         temp.append(re_path(r'^(\d+)/change/$',self.change_view))

         return temp,None,None

 class XadminSite(object):
     def __init__(self):
         self._registry = {}

     def register(self,model,Xadmin_class=None,**options):
         if not Xadmin_class:
             Xadmin_class = ModelXadmin
         self._registry[model] = Xadmin_class(model,self)  #{Book:ModelXadmin(Book)}

     @property
     def urls(self):

         temp = []

         for model,Xadmin_class in self._registry.items():
             app_name = model._meta.app_label   #取相应app的名字
             model_name = model._meta.model_name   #取相应model的名字

             temp.append(re_path(r'^{0}/{1}/'.format(app_name,model_name),Xadmin_class.urls))#

         return temp,None,None

 site = XadminSite()  #创建单例对象

在app的Xadmin.py中:

 from Xadmin.service import Xadmin
 from app02 import models

 Xadmin.site.register(models.Food)
 Xadmin.site.register(models.Order)
05-12 12:52