django的url采用正則表達式進行配置,雖然強大卻也廣為詬病。反對者們認為django的url配置過于繁瑣,且不支持默認的路由功能。
我倒覺得還好,只是如果覺得不爽,為什么不自己小小的hack一下,反正也就幾行代碼的事。
在這個背景下,我整了這個url_helper,利用url_helper可以簡化配置和實現url的默認路由。所謂的url_helper其實就只有url_helper.py一個文件,使用的時候只想要import就可以。
url_helper的具體用法請參考具體的例子:
url_helper下載/范例
下面對使用方法做個簡單的說明。
url的默認路由
?
from url_helper import execute, url_ import views urlpatterns += patterns('', url(r'^(?P.*)', execute, {'views': views}), )
在urls.py里增加如下配置,其中views為需要進行路由的views模塊。url的規則為 /action/param1/param2/…/ 。
例如:
?
#/edit/4/ def edit(request, n="id"): html = """ edit object: %s""" % n return HttpResponse(html)
在沒有指定action的時候默認使用的action為index。
提供函數url_簡化url配置
仿照ROR的做法,參數用”:”標識。
例如:
?
#url_(r'/space/:username/:tag/', views.url_), #/space/vicalloy/just/ def url_(request, username, tag): html = """ username: %s
tag: %s""" % (username, tag) return HttpResponse(html)
url_helper的完整代碼
就如前面說的,代碼非常少。不過實際應用的話,應當還需要做一些擴展。
?
#!/usr/bin/env python # -*- coding: UTF-8 -*- from django import http from django.conf.urls.defaults import url import 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)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
