Login

Default URL handler

Author:
solartic
Posted:
April 19, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Default URL handler allows views to be loaded without defining them in the urls.py. Views will therefore be loaded based on the pattern of the browser url. For example http://host/app_name/view_name will load project_name.app_name.views.view_name. Though I would not used this in production, it can be used to speed-up development.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#==============================================================================
# settings.py
#==============================================================================

import os

PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
PROJECT_NAME = os.path.basename(PROJECT_ROOT)


#==============================================================================
# urls.py
#==============================================================================

urlpatterns = patterns('',
    (r'^.+/', 'project.lib.views.default'), # '^.+/' preserves Django's APPEND_SLASH feature
)


#==============================================================================
# project.lib.views.py
#==============================================================================

from django.conf import settings
from django.http import Http404

def default(request):
    split_url = request.path.strip('/').split('/')
    
    project_name    = settings.PROJECT_NAME
    app_name        = split_url[0]
    view_name       = split_url[1]
    
    import_string = '%s.%s.views' % (project_name,app_name)
  
    try:
        module  = __import__(import_string)
        app     = getattr(module, app_name)
        views   = getattr(app, 'views')
        
        return getattr(views, view_name)(request)
    except:
        raise Http404

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.