搜索
首页后端开发Python教程使用url_helper简化Python中Django框架的url配置教程

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'^(&#63;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: "(&#63;P<%s>[^/]+)" % matchobj.group(0)[1:],
      regex)
  return url(regex, *args[1:], **dic)

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何切成python阵列?您如何切成python阵列?May 01, 2025 am 12:18 AM

Python列表切片的基本语法是list[start:stop:step]。1.start是包含的第一个元素索引,2.stop是排除的第一个元素索引,3.step决定元素之间的步长。切片不仅用于提取数据,还可以修改和反转列表。

在什么情况下,列表的表现比数组表现更好?在什么情况下,列表的表现比数组表现更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/删除,2)储存的二聚体和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何将Python数组转换为Python列表?如何将Python数组转换为Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,请考虑performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

当Python中存在列表时,使用数组的目的是什么?当Python中存在列表时,使用数组的目的是什么?May 01, 2025 am 12:04 AM

choosearraysoverlistsinpythonforbetterperformanceandmemoryfliceSpecificScenarios.1)largenumericaldatasets:arraysreducememoryusage.2)绩效 - 临界杂货:arraysoffersoffersOffersOffersOffersPoostSfoostSforsssfortasssfortaskslikeappensearch orearch.3)testessenforcety:arraysenforce:arraysenforc

说明如何通过列表和数组的元素迭代。说明如何通过列表和数组的元素迭代。May 01, 2025 am 12:01 AM

在Python中,可以使用for循环、enumerate和列表推导式遍历列表;在Java中,可以使用传统for循环和增强for循环遍历数组。1.Python列表遍历方法包括:for循环、enumerate和列表推导式。2.Java数组遍历方法包括:传统for循环和增强for循环。

什么是Python Switch语句?什么是Python Switch语句?Apr 30, 2025 pm 02:08 PM

本文讨论了Python版本3.10中介绍的新“匹配”语句,该语句与其他语言相同。它增强了代码的可读性,并为传统的if-elif-el提供了性能优势

Python中有什么例外组?Python中有什么例外组?Apr 30, 2025 pm 02:07 PM

Python 3.11中的异常组允许同时处理多个异常,从而改善了并发场景和复杂操作中的错误管理。

Python中的功能注释是什么?Python中的功能注释是什么?Apr 30, 2025 pm 02:06 PM

Python中的功能注释将元数据添加到函数中,以进行类型检查,文档和IDE支持。它们增强了代码的可读性,维护,并且在API开发,数据科学和图书馆创建中至关重要。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境