python curd设计

 

在django项目中创建stack app,创建service package ,在其中创建v1.py

from django.shortcuts import HttpResponse,render,redirect
from django.urls import reverse
from django.urls import path,re_path
from django.forms import ModelForm
class StackConf(object):
    '''
    用于封装单独操作数据库的类
    '''
    list_display=[]
    model_form_cls=None
    def __init__(self,mcls):
        self.mcls=mcls

    @property
    def urls(self):
        app_model_name=(self.mcls._meta.app_label,self.mcls._meta.model_name)
        patterns=[
            path('',self.changelist_view,name='%s_%s_changelist'%(app_model_name)),
            path('add',self.add_view,name='%s_%s_add'%(app_model_name)),
            re_path('(\d+)/change/',self.change_view,name='%s_%s_change'%(app_model_name)),
            re_path('(\d+)/delete/',self.delete_view,name='%s_%s_delete'%(app_model_name)),
        ]
        patterns.extend(self.extend_urls())
        return patterns
    def extend_urls(self):
        '''
        钩子函数
        :return:
        '''
        ext_urls=[]
        return ext_urls

    def get_model_form_cls(self):
        if self.model_form_cls:
            return self.model_form_cls
        class TempModelForm(ModelForm):
            class Meta:
                model=self.mcls
                fields="__all__"
        return TempModelForm

    def changelist_view(self,request):
        mcls_dict = self.mcls.objects.all()
        #处理表头
        head_list=[]
        for item in self.list_display:
            temp=self.mcls._meta.get_field(item).verbose_name
            head_list.append(temp)
        #处理表内容
        body_list=[]
        for body_item in mcls_dict:
            body_temp=[]
            for n in self.list_display:
                body_temp.append(getattr(body_item,n))
            body_list.append(body_temp)
        #处理添加按钮
        app_model_name = (self.mcls._meta.app_label, self.mcls._meta.model_name,)
        name = "stack:%s_%s_add" % app_model_name
        add_url=reverse(name)
        #return HttpResponse('列表页面')
        return  render(request,'list.html',{'head_list':head_list,'body_list':body_list,"add_url":add_url})

    def add_view(self,request):
        model_form_class=self.get_model_form_cls()
        if request.method=='GET':
            form=model_form_class()
            return render(request,'add_view.html',{'form':form})
        else:
            form=model_form_class(request.POST)
            if form.is_valid():
                form.save()
                #跳转到列表页面
                app_model_name = (self.mcls._meta.app_label, self.mcls._meta.model_name,)
                name='stack:%s_%s_changelist' %app_model_name
                list_url=reverse(name)
                return redirect(list_url)
            return render(request,'add_view.html',{'form':form})
        #return HttpResponse('添加页面')

    def change_view(self,request,id):
        return HttpResponse('更新页面')

    def delete_view(self,request,id):
        return HttpResponse('删除页面')
class StackSite(object):
    '''
    用于封装所有数据库操作的类
    '''
    def __init__(self):
        self._registry={}
    def register(self,model_class,conf_cls=None):
        if not conf_cls:
           conf_cls=StackConf
        self._registry[model_class]=conf_cls(model_class)

    @property
    def urls(self):
        ptl=[
            path('login/',self.login),
        ]
        for model_class,config_obj in self._registry.items():
            app_label=model_class._meta.app_label
            model_name=model_class._meta.model_name
            tmp=path('%s/%s/'%(app_label,model_name),(config_obj.urls,None,None))
            #tmp = path('%s/%s/' % (app_label, model_name),self.login)
            ptl.append(tmp)
        return ptl,'stack',None
    def login(self,request):
        return HttpResponse('登录页面')
site=StackSite()

在django项目中创建测试 app   

  app01,创建stack.py   注册 app01中的models.py中的数据库表到 stack app 中

# print('sakula,this is stack.')
from app01 import  models
from stack.service import  v1
from stack.service.v1 import site
from django.shortcuts import render
from django.urls import path
from django.forms import ModelForm
from django.forms import fields
class UserInfoModelForm(ModelForm):
    xx=fields.CharField(max_length=32)
    class Meta:
        model=models.UserInfo
        fields="__all__"
class UserInfoConf(v1.StackConf):
    model_form_cls = UserInfoModelForm
    list_display = ['id','username','password']
    # def changelist_view(self,request):
    #     mcls_dict=self.mcls.objects.all()
    #     #return HttpResponse('列表页面')
    #     return  render(request,'list_conf.html',{'result_list':mcls_dict})

#实现钩子函数 完成 url页面的扩展
class RoleConf(v1.StackConf):
    #数据的展示自定义
    list_display = ['id','title']
    def extend_urls(self):
        patterns=[
            path('xxx',self.xxx),
        ]
        return patterns
    def xxx(self,request):
        return render(request,'xxx.html')
site.register(models.UserInfo,UserInfoConf)
site.register(models.Role,RoleConf)

在django项目中 urls.py 中 配置url的访问入口

"""my2_curd URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from stack.service import v1
urlpatterns = [
    path('admin/', admin.site.urls),
    path('stack/',v1.site.urls,),
]

 

posted @ 2018-09-01 17:49  hexintong  阅读(282)  评论(0编辑  收藏  举报