stark - 注册表、生成url
一、配置
stark组件开发,仿django自带得admin组件。
1. startapp stark
2. settings: 'stark.apps.StarkConfig'
3. 启动就执行
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class StarkConfig(AppConfig): name = 'stark' # 程序启动时,扫描app下得指定文件(stark.py)并执行 def ready(self): autodiscover_modules('stark')
4.models.py (一对一,一对多,多对多)
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() # 与AuthorDetail建立一对一的关系 authorDetail = models.OneToOneField(to="AuthorDetail",to_field="nid", on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.BigIntegerField() addr = models.CharField(max_length=64) def __str__(self): return str(self.telephone) class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(verbose_name='名称', max_length=32) publishDate = models.DateField() price = models.DecimalField(verbose_name='价格', max_digits=5,decimal_places=2) # 与Publish建立一对多的关系,外键字段建立在多的一方 publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors = models.ManyToManyField("Author") def __str__(self): return self.title
makemigrations
migrate
createsuperuser (yuan yuan1234)
5.admin.py
from django.contrib import admin # Register your models here. from .models import * class BookConfig(admin.ModelAdmin): list_display = ['title', 'price', 'publish'] list_filter = ['title', 'publish', 'authors'] # list_display_links = ['price'] def patch_init(self, request, queryset): print(queryset) # <QuerySet [<Book: shu 2>, <Book: gOy>]> queryset.update(price=100) patch_init.short_description = '批量初始化' actions = [patch_init] admin.site.register(Book, BookConfig) admin.site.register(Author) admin.site.register(AuthorDetail) admin.site.register(Publish)
二、注册表
知识点:
单例对象,全局得!
site = StarkSite()
注册:{ ... }
self._registry[model] = stark_class(model,self)
stark.site.register(Book, BookConfig)
stark.site.register(Publish)
print(stark.site._registry)
{<class 'app01.models.Book'>: <app01.stark.BookConfig object at 0x000002423EC9F710>,
<class 'app01.models.Publish'>: <stark.service.stark.ModelStark object at 0x000002423EC9F748>,
stark/service/stark.py (单例)
class ModelStark(object): list_display = [] def __init__(self, model, site): self.model = model self.site = site class StarkSite(object): def __init__(self): self._registry = {} def register(self, model, stark_class=None): if not stark_class: stark_class = ModelStark self._registry[model] = stark_class(model,self) site = StarkSite()
app01/stark.py
from stark.service import stark from .models import * class BookConfig(stark.ModelStark): pass stark.site.register(Book, BookConfig) stark.site.register(Publish) stark.site.register(Author) stark.site.register(AuthorDetail) print(stark.site._registry) """ {<class 'app01.models.Book'>: <app01.stark.BookConfig object at 0x000002423EC9F710>, <class 'app01.models.Publish'>: <stark.service.stark.ModelStark object at 0x000002423EC9F748>, <class 'app01.models.Author'>: <stark.service.stark.ModelStark object at 0x000002423EC9F898>, <class 'app01.models.AuthorDetail'>: <stark.service.stark.ModelStark object at 0x000002423EC9FCC0>} """
三、生成url
知识点:
1. url分发:
url(r'^stark/', ([],None,None))
url(r'^stark/', stark.site.urls)
@property
def urls(self):
return self.get_urls(), None, None
2. 用户可以自定制配置页面,所以调用配置类 stark_class_obj.urls2
# 分发增删改查
temp.append(url(r'%s/%s/'%(app_label,model_name), stark_class_obj.urls2))
3. 名称空间,之后可以反向解析,灵活应用
model_name = self.model._meta.model_name
app_label = self.model._meta.app_label
# print(model_name, app_label)
"""
book app01
publish app01
author app01
authordetail app01
"""
temp.append(url(r'add/', self.add_view, name="%s_%s_add" % (app_label, model_name)))
temp.append(url(r'(\d+)/delete/', self.delete_view, name="%s_%s_delete" % (app_label, model_name)))
temp.append(url(r'(\d+)/change/', self.change_view, name="%s_%s_change" % (app_label, model_name)))
temp.append(url(r'^$', self.list_view, name="%s_%s_list" % (app_label, model_name)))
4.ModelStark
ModelStark()
self.model:用户访问的模型表
urls.py
from django.conf.urls import url from django.contrib import admin from stark.service import stark urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^stark/', stark.site.urls) ]
stark/service/stark.py (url分发)
from django.conf.urls import url from django.shortcuts import HttpResponse, reverse, redirect class ModelStark(object): list_display = [] def __init__(self, model, site): self.model = model self.site = site def add_view(self, request): return HttpResponse('add_view') def delete_view(self, request, delete_id): return HttpResponse('delete_view') def change_view(self, request, change_id): return HttpResponse('change_view') def list_view(self, request): return HttpResponse('list_view') def get_urls2(self): temp = [] model_name = self.model._meta.model_name app_label = self.model._meta.app_label # print(model_name, app_label) """ book app01 publish app01 author app01 authordetail app01 """ temp.append(url(r'add/', self.add_view, name="%s_%s_add" % (app_label, model_name))) temp.append(url(r'(\d+)/delete/', self.delete_view, name="%s_%s_delete" % (app_label, model_name))) temp.append(url(r'(\d+)/change/', self.change_view, name="%s_%s_change" % (app_label, model_name))) temp.append(url(r'^$', self.list_view, name="%s_%s_list" % (app_label, model_name))) return temp @property def urls2(self): return self.get_urls2(), None, None class StarkSite(object): def __init__(self): self._registry = {} def register(self, model, stark_class=None): if not stark_class: stark_class = ModelStark self._registry[model] = stark_class(model,self) def get_urls(self): temp = [] # 模型表,配置类对象 for model, stark_class_obj in self._registry.items(): # print(model,'---',stark_class_obj) """ <class 'app01.models.Book'> --- <app01.stark.BookConfig object at 0x000001F03A8BF7F0> <class 'app01.models.Publish'> --- <stark.service.stark.ModelStark object at 0x000001F03A8BF748> """ model_name = model._meta.model_name app_label = model._meta.app_label # 分发增删改查 temp.append(url(r'%s/%s/'%(app_label,model_name), stark_class_obj.urls2))
"""
path('app01/userinfo/',UserConfig(Userinfo,site).urls2),
path('app01/book/',ModelStark(Book,site).urls2),
"""
return temp @property def urls(self): return self.get_urls(), None, None site = StarkSite()