zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    2017秋-软件工程第三次作业(3)
    第二周例行总结
    2017秋-软件工程第二次作业
    2017秋-软件工程第一次作业
    ORA-01502: 索引或这类索引的分区处于不可用状态
    Merge into使用详解
    SQL2008中Merge的用法
    system表空间用满解决
    Oracle:ORA-00604: 递归 SQL 级别 1 出现错误
    AIX系统上压缩与解压文件
  • 原文地址:https://www.cnblogs.com/zijiyanxi/p/5561307.html
Copyright © 2011-2022 走看看