使用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-numpy实现灰度图像的分块和合并方式

我就废话不多说了,直接上代码吧! from numpy import * import numpy as np import cv2, os, math, os.path from...

Django进阶之CSRF的解决

Django进阶之CSRF的解决

简介 django为用户实现防止跨站请求伪造的功能,通过中间件 django.middleware.csrf.CsrfViewMiddleware 来完成。而对于django中设置防跨站...

使用python去除图片白色像素的实例

以下代码是把一个文件夹里的所有图片的 白色像素去掉,制作透明png图片 需要python和pil from PIL import Image import os for fil...

初步解析Python中的yield函数的用法

您可能听说过,带有 yield 的函数在 Python 中被称之为 generator(生成器),何谓 generator ? 我们先抛开 generator,以一个常见的编程题目来展示...

使用Django启动命令行及执行脚本的方法

使用django启动命令行和脚本,可以方便的使用django框架做开发,例如,数据库的操作等。 下面分别介绍使用方法。 django shell的启动 启动命令: $/data/py...