app01/views.py
from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse("index")
luffy.py
from django.urls import re_path from app01 import views class StarkSite(object): def __init__(self): # 类变量定义一个空列表,两个app下的xxx.py在项目启动时且在加载路由前,会往此列表中各添加一个元素,'app01'和'app02' self._registry = [] def get_urls(self): # 定义一个空列表,此空列表作用相当于是子路由列表 patterns = [] # 循环类变量所定义的列表,此时列表已有两个元素,['app01', 'app02'],按照子路由的格式进行拼接并添加到patterns列表中 for app in self._registry: patterns.append(re_path(r'^%s/$' % app, views.index)) return patterns @property def urls(self): # 返回一个有三个元素的元组,供总路由调用 return (self.get_urls(), None, None) site = StarkSite()
app01/apps.py
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class App01Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app01' def ready(self): autodiscover_modules("xxx")
app01/xxx.py
from luffy import site site._registry.append("app01")
app02/xxx.py
from luffy import site site._registry.append("app02")
djangoProject/urls.py
from django.urls import re_path from luffy import site urlpatterns = [ re_path(r'^web/', site.urls), # 调用luffy.py文件中的urls方法 ]
启动Django项目,前端输入路由进行查看