• Django模拟ASP.NET MVC 自动匹配路由(转载)


    项目结构

    操作步骤

    1.创建项目结构如上图

    2.在myapp目录下创建urls文件,代码:

    1 from django.conf.urls import patterns, url
    2 
    3 from untitled1.myapp.dispatcher import start
    4 
    5 urlpatterns = patterns('',
    6                        url(r'^(?P<controller>w+)?/(?P<action>w+)?/(?P<parameter>.+)?$', start),
    7                        )

    3.创建dispatcher文件,代码:

     1 import inspect
     2 
     3 from untitled1 import common
     4 from untitled1.response import response
     5 
     6 
     7 def start(request, controller, action, parameter):
     8     # initialize controller, execute action with parameter
     9     prefix = 'untitled1.myapp.'
    10 
    11     namespace = prefix + controller
    12     __import__(namespace)
    13     module = common.common.import_module(namespace)
    14 
    15     methods = [k for k, v in inspect.getmembers(module) if k == action]
    16     if len(methods) <= 0:
    17         return response.http404()
    18 
    19     return getattr(module, methods[0])(request)

    4.创建views文件,代码:

     1 def list(request): 2 return render(request, "index.html") 

    5.在untitled1目录下创建common文件,代码:

     1 class common:
     2 
     3     @staticmethod
     4     def import_module(namespace):
     5         components = namespace.split('.')
     6         if len(components) == 1:
     7             return globals()[namespace]
     8 
     9         module = __import__(components[0])
    10         for compent in components[1:]:
    11             module = getattr(module, compent)
    12 
    13         return module

    6.配置untitle1的urls文件,代码:

    1 from django.conf.urls import url, include
    2 from django.contrib import admin
    3 
    4 urlpatterns = [
    5     url(r'^admin/', admin.site.urls),
    6     url(r'^myapp/', include("untitled1.myapp.urls")),
    7 ]

    7.访问方式:

    http://localhost/myapp/views/list

    原文参考:

    http://bbs.51aspx.com/archiver/showtopic-44319.html

  • 相关阅读:
    IDEA新字体出现啦!!!
    Spring学习笔记1---Bean的自动装配
    Spring学习笔记1---Bean的作用域
    Spring学习笔记1---C命名和P命名的注入
    Spring学习笔记1---IoC创建对象的方式
    Spring学习笔记1---IoC容器
    Spring学习笔记1---IOC理论推导
    vfatbGUbLE
    Spring学习笔记1---环境配置(IDEA)
    springboot整合ES
  • 原文地址:https://www.cnblogs.com/zijiyanxi/p/5561307.html
Copyright © 2020-2023  润新知