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

yipeiwu_com5年前Python基础

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<urls>.*)', 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 <br/> 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)

相关文章

Python实现对excel文件列表值进行统计的方法

本文实例讲述了Python实现对excel文件列表值进行统计的方法。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding=gbk #此PY用来...

windows及linux环境下永久修改pip镜像源的方法

windows及linux环境下永久修改pip镜像源的方法

一、在windows环境下修改pip镜像源的方法(以python3.5为例) (1):在windows文件管理器中,输入 %APPDATA% (2):会定位到一个新的目录下,在该目...

利用python读取YUV文件 转RGB 8bit/10bit通用

注:本文所指的YUV均为YUV420中的I420格式(最常见的一种),其他格式不能用以下的代码。 位深为8bit时,每个像素占用1字节,对应文件指针的fp.read(1); 位深为10b...

Python线程下使用锁的技巧分享

使用诸如Lock、RLock、Semphore之类的锁原语时,必须多加小心,锁的错误使用很容易导致死锁或相互竞争。依赖锁的代码应该保证当出现异常时可以正常的释放锁。 典型代码如下:...

Python中属性和描述符的正确使用

关于@property装饰器 在Python中我们使用@property装饰器来把对函数的调用伪装成对属性的访问。 那么为什么要这样做呢?因为@property让我们将自定义的代码同变量...