Django之URL配置及动态路由

发布于 2018-06-09  331 次阅读


普通情况

from kingWeb.adm.views import home
from kingWeb.adm.views import control
from kingWeb.adm.views import user
 
urlpatterns = [
   url(r'^$',home.index, name='home'),
   url(r'^control$',control.index, name='control_default'),
   url(r'^control/index',control.index, name='control_index'),
   url(r'^control/welcome',control.welcome, name='control_welcome'),
]




带参数

urlpatterns = [
   url(r'^host/(\d+)$', views.host),
   url(r'^host_list/(\d+)/(\d+)$', views.host_list),
   url(r'^user/edit/(?P<id>[0-9]+)/$',user.edit,name="user_edit"), #带参数的 后台接收参数名为id ,正则表达式的分组,相当于一个字典
]

\^host/(\d+)$
相对应的url是: ”http://127.0.0.1/host/2“ (\d+)是匹配任意的数字,在分页时灵活运用。
在views.host中需要指定一个形式参数来接受(\d+)\$ 的值

def host(request,id): return HttpResponse(id) 

按照不同app引用规则

urlpatterns = [
   url(r'^app01/', include('app01.urls')),
   url(r'^app02/', include('app02.urls')),
]

用的时候发现,这样的话要每个url都得写个配置,于是网上找了下看到个通过反射机制实现动态路由,就和.NET mvc那路由一样了

新建个文件activator.py,具体细节看自己需求在此基础上修改

from django.shortcuts import render_to_response,HttpResponse,redirect
from kingWeb.models import ResultModel,SysOperationLog
from kingWeb.util.WebHelper import *
import json
def process(request,**kwargs):
    '''接收所有匹配url的请求,根据请求url中的参数,通过反射动态指定view中的方法'''
 
    app = kwargs.get('app',None)
    controller = kwargs.get('controller',None)
    action = kwargs.get('action',None)
 
    ip = WebHelper.get_client_ip(request)
    agent = WebHelper.get_client_agent(request)
    user = request.user
    url = request.get_full_path()
    SysOperationLog.objects.create(clientip=ip,clientinfo = agent,username=user.username,operationdescription='访问',\
        operationurl = url)
 
    try:
        viewObj = __import__("%s.%s.views" % ('kingWeb',app),fromlist=(controller,))
        ctrlObj = getattr(viewObj, controller)
        actionObj = getattr(ctrlObj, action)
        #执行view.py中的函数,并获取其返回值
        result = actionObj(request,kwargs)
        return result
    except(ImportError,AttributeError) as e:
        if request.method == 'POST':
            result = ResultModel()
            result.flag = False
            result.msg = '操作失败:' + str(e)
            return HttpResponse(json.dumps(result.tojson()), content_type="application/json")
        else:
           return redirect('/adm/home/notfound')
    except Exception as e:
        if request.method == 'POST':
            result = ResultModel()
            result.flag = False
            result.msg = '操作失败:' + str(e)
            return HttpResponse(json.dumps(result.tojson()), content_type="application/json")
        else:
            return redirect('/adm/home/error')

然后新建个动态路由需要的urls.py

因为之前用的.net mvc,所以这里也给写成controller和action了,看着习惯,下面的process则是上面那个activator

from django.conf.urls import url,include
import django.contrib.auth.views
from kingWeb.DynamicRouter.activator import process
from django.contrib import admin
urlpatterns = [
    # url(r'^adm/', include('kingWeb.adm.urls'))
    url(r'^admin/', include(admin.site.urls)),
       url('^(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\d+))/$',process),
              url('^(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\d+))/(?P(\d+))/$',process),
           url('^(?P(\w+))/(?P(\w+))/(?P(\w+))/$',process),
             url('^(?P(\w+))/(?P(\w+))/$',process,{'action':'index'}), #控制器默认首页 index
                url('^(?P(\w+))/$',process,{'controller':'home','action':'index'}), #默认首页/adm/home/index
   ]
 

然后需要修改settings.py中为你这个动态路由的urls.py

ROOT_URLCONF = 'kingWeb.DynamicRouter.urls'

还有注意,要在对应的views.py里加上 from kingWeb.DynamicRouter import urls,不然会报错

from kingWeb.DynamicRouter import urls
def index(request,kwargs):
    assert isinstance(request, HttpRequest)
    return render(request,
        'adm/user/index.html',
        {
            'title':'用户管理',
        })

LoneKing