This article mainly introduces how to use url_helper to simplify the url configuration of Django framework in Python. if you need it, you can refer to django's url and configure it using regular expressions. although it is powerful, it is also widely criticized. Opponents think that django's url configuration is too cumbersome and does not support the default routing function.
I think it's okay, but if I feel uncomfortable, why isn't I just a little hack? it's just a few lines of code.
In this context, I have integrated the url_helper and use url_helper to simplify the configuration and implement the default url routing. The so-called url_helper actually only has a file named url_helper.py. you only need to import the file.
For the usage of url_helper, see the example below:
Url_helper download/example
The following is a simple description of the usage method.
Default url route
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 is the view module for routing. The url rule is/action/param1/param2 /... /.
For example:
#/edit/4/ def edit(request, n="id"): html = """ edit object: %s""" % n return HttpResponse(html)
When no action is specified, the default action is index.
Provide function url _ simplify url configuration
Like ROR, the parameter is marked.
For example:
#url_(r'/space/:username/:tag/', views.url_), #/space/vicalloy/just/ def url_(request, username, tag): html = """ username: %s
tag: %s""" % (username, tag) return HttpResponse(html)
Complete url_helper code
As mentioned above, there are very few codes. However, some extensions are needed for 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)