国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用url_helper簡化Python中Django框架的url配置教程

2019-11-25 17:20:42
字體:
供稿:網(wǎng)友

django的url采用正則表達(dá)式進(jìn)行配置,雖然強(qiáng)大卻也廣為詬病。反對者們認(rèn)為django的url配置過于繁瑣,且不支持默認(rèn)的路由功能。

我倒覺得還好,只是如果覺得不爽,為什么不自己小小的hack一下,反正也就幾行代碼的事。

在這個背景下,我整了這個url_helper,利用url_helper可以簡化配置和實(shí)現(xiàn)url的默認(rèn)路由。所謂的url_helper其實(shí)就只有url_helper.py一個文件,使用的時候只想要import就可以。

url_helper的具體用法請參考具體的例子:

url_helper下載/范例

下面對使用方法做個簡單的說明。
url的默認(rèn)路由

 

from url_helper import execute, url_import views urlpatterns += patterns('',  url(r'^(?P<urls>.*)', execute, {'views': views}),)

在urls.py里增加如下配置,其中views為需要進(jìn)行路由的views模塊。url的規(guī)則為 /action/param1/param2/…/ 。

例如:

 

#/edit/4/ def edit(request, n="id"):  html = """ edit object: %s""" % n  return HttpResponse(html)

在沒有指定action的時候默認(rèn)使用的action為index。
提供函數(shù)url_簡化url配置

仿照ROR的做法,參數(shù)用”:”標(biāo)識。

例如:
 

#url_(r'/space/:username/:tag/', views.url_), #/space/vicalloy/just/ def url_(request, username, tag):  html = """ username: %s <br/> tag: %s""" % (username, tag)  return HttpResponse(html)

url_helper的完整代碼

就如前面說的,代碼非常少。不過實(shí)際應(yīng)用的話,應(yīng)當(dāng)還需要做一些擴(kuò)展。

 

#!/usr/bin/env python# -*- coding: UTF-8 -*-from django import httpfrom django.conf.urls.defaults import urlimport re def execute(request, urls, views):  """  urls [methodName/]param1/param2/.../  methodName default index  """  def get_method(views, methodName):    try:      return getattr(views, methodName)    except Exception, e:      return None  method = None  params = [e for e in urls.split("/") if e]  params.reverse()  if params:    method = get_method(views, params.pop())  if not method:    method = get_method(views, 'index')  if not method:    raise http.Http404('The requested admin page does not exist.')  return method(request, *params) def url_(*args,**dic):  regex = args[0]  if regex[0] == "/":    regex = regex[1:]  regex = '^' + regex  regex = regex + '$'  regex = re.sub(":[^/]+",      lambda matchobj: "(?P<%s>[^/]+)" % matchobj.group(0)[1:],      regex)  return url(regex, *args[1:], **dic)

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 晋江市| 汤原县| 元阳县| 繁昌县| 宝丰县| 周至县| 绥阳县| 桐柏县| 中山市| 东宁县| 韶关市| 孟连| 会理县| 西华县| 英山县| 互助| 辉南县| 余庆县| 广汉市| 若羌县| 敦化市| 金堂县| 禄劝| 英吉沙县| 丹凤县| 会理县| 丹阳市| 上虞市| 张北县| 灌阳县| 汶川县| 神农架林区| 上蔡县| 沿河| 阿坝县| 宽城| 青铜峡市| 汤原县| 石泉县| 灌南县| 黄大仙区|