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

來源:互聯網
上載者:User

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

   這篇文章主要介紹了使用url_helper簡化Python中Django架構的url配置教程,需要的朋友可以參考下

  django的url採用Regex進行配置,雖然強大卻也廣為詬病。反對者們認為django的url配置過於繁瑣,且不支援預設的路由功能。

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

  在這個背景下,我整了這個url_helper,利用url_helper可以簡化配置和實現url的預設路由。所謂的url_helper其實就只有url_helper.py一個檔案,使用的時候只想要import就可以。

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

  url_helper下載/範例

  下面對使用方法做個簡單的說明。

  url的預設路由

  ?

1

2

3

4

5

6

from url_helper import execute, url_

import views

 

urlpatterns += patterns('',

url(r'^(?P<urls>.*)', execute, {'views': views}),

)

  在urls.py裡增加如下配置,其中views為需要進行路由的views模組。url的規則為 /action/param1/param2/…/ 。

  例如:

  ?

1

2

3

4

5

#/edit/4/

 

def edit(request, n="id"):

html = """ edit object: %s""" % n

return HttpResponse(html)

  在沒有指定action的時候預設使用的action為index。

  提供函數url_簡化url配置

  仿照ROR的做法,參數用”:”標識。

  例如:

  ?

1

2

3

4

5

6

#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的完整代碼

  就如前面說的,代碼非常少。不過實際應用的話,應當還需要做一些擴充。

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

#!/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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.