Login

Default URL handler

Author:
solartic
Posted:
April 19, 2011
Language:
Python
Version:
1.2
Tags:
url
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. Using class methods as views by panyam 5 years, 10 months ago
  2. Use MEDIA_URL in 500 error page by bthomas 6 years, 5 months ago
  3. A custom 500 handler which is AJAX-aware by mallipeddi 7 years, 2 months ago
  4. View and StatefulView classes by Digitalxero 6 years, 6 months ago
  5. Default Template Loading by nirvdrum 7 years, 8 months ago

Comments

Please login first before commenting.