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

 

posted @ 2016-06-05 18:05  逆风飞行  阅读(512)  评论(0编辑  收藏  举报