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

yipeiwu_com6年前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和mysql交互操作实例详解【基于pymysql库】

python和mysql交互操作实例详解【基于pymysql库】

本文实例讲述了python和mysql交互操作。分享给大家供大家参考,具体如下: python要和mysql交互,我们利用pymysql这个库。 下载地址: https://github...

Python学习小技巧总结

三元条件判断的3种实现方法 C语言中有三元条件表达式,如 a>b?a:b,Python中没有三目运算符(?:),但Python有它自己的方式来实现类似的功能。这里介...

Python中文件I/O高效操作处理的技巧分享

如何读写文本文件? 实际案例 某文本文件编码格式已直(如UTF-8,GBK,BIG5),在python2.x和python3.x中分别如何读取这些文件? 解决方案 字符串的语义发生了变化...

pytorch三层全连接层实现手写字母识别方式

pytorch三层全连接层实现手写字母识别方式

先用最简单的三层全连接神经网络,然后添加激活层查看实验结果,最后加上批标准化验证是否有效 首先根据已有的模板定义网络结构SimpleNet,命名为net.py import torc...

关于Pytorch的MNIST数据集的预处理详解

关于Pytorch的MNIST数据集的预处理详解

关于Pytorch的MNIST数据集的预处理详解 MNIST的准确率达到99.7% 用于MNIST的卷积神经网络(CNN)的实现,具有各种技术,例如数据增强,丢失,伪随机化等。 操作系统...