Django URLs are configured with regular expressions, though powerful and widely criticized. Opponents argue that Django's URL configuration is too cumbersome and does not support the default routing feature.
I think it is OK, just if feel uncomfortable, why not their own small hack, anyway, just a few lines of code.
In this context, I've made this url_helper, the use of Url_helper simplifies the configuration and implementation of default routes for URLs. The so-called url_helper in fact only url_helper.py a file, use when only want to import.
For specific use of url_helper, please refer to specific examples:
Url_helper Download/Example
Here is a simple explanation of how to use the method.
Default route for URLs
From Url_helper Import Execute, url_import views urlpatterns + = Patterns ("', url (r ' ^ (? P
. *) '
, execute, {' Views ': views})
Add the following configuration in urls.py, where views are the views module that needs to be routed. The rules for URLs are/action/param1/param2/.../.
For example:
#/edit/4/def edit (Request, n= "id"): html = "" "Edit object:%s" ""% n return HttpResponse (HTML)
The action that is used by default when no action is specified is index.
Provides function Url_ simplifies URL configuration
Modelled on Ror's approach, the parameters are identified with ":".
For example:
#url_ (R '/space/:username/:tag/', views.url_), #/space/vicalloy/just/def url_ (request, username, tag):
Tag:%s "" "% (username, tag) return HttpResponse (HTML)
Complete code for Url_helper
As I said earlier, the code is very small. However, some extensions should be made in practical applications.
#!/usr/bin/env python#-*-coding:utf-8-*-from Django import httpfrom django.conf.urls.defaults import Urlimport 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)