Login

Automating URLs

Author:
jorjun
Posted:
June 23, 2009
Language:
Python
Version:
1.0
Tags:
rest url
Score:
0 (after 0 ratings)

This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.

 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
44
45
46
47
48
49
# models.py
# - - - - - - - - 
from django.conf.urls.defaults import patterns, url

class Accessor(object):
    @classmethod
    def get_url_patterns(cls):
        model = cls._meta.object_name.lower()
        acc = []
        if 'get' in cls.access:
            acc.append((r'^%s/(?P<id>\d+)/get/$' %model, '%s_get' % model))
            acc.append((r'^%s/page/(?P<page>\d+)/get/$' % model, '%s_page_get' % model))
        if 'new' in cls.access:
            acc.append((r'^%s/new/post/$' % model, '%s_new_post' % model))
            acc.append((r'^%s/new/get/$' % model, '%s_new_get' % model))
        return [url(*p) for p in acc]

    @classmethod
    def get_default_page(cls):
        app = cls._meta.app_label.lower()
        model = cls._meta.object_name.lower()
        return '/%s/%s/page/1/get/' %(app, model)

class Private(Accessor):
    access = ()

class All(Accessor):
    access = ('get', 'new')

class ReadOnly(Accessor):
    access = ('get',)

class Admin(Accessor):
    access = All.access + ('admin',)

# - - - - - - - - 
utils.py
# - - - - - - - - 
from django.contrib.contenttypes.models import ContentType
from django.conf.urls.defaults import patterns


def get_model_paths(app_label):
    urls = []
    for content in ContentType.objects.filter(app_label=app_label):
        model = models.get_model(app_label=content.app_label, model_name=content.model)
        if hasattr(model, 'get_url_patterns'):
            urls.extend(model.get_url_patterns())
    return patterns('myapp.Main.views', *urls)

More like this

  1. Callable Class View by zbyte64 7 years, 3 months ago
  2. Decouple 'help_text' attribute from field definition by kmike 5 years ago
  3. FieldsetForm by Ciantic 8 years, 4 months ago
  4. Form and FormSet that are defined dynamically with request-data by Lacour 5 years, 7 months ago
  5. Declaring django views like web.py views by danigm 5 years, 6 months ago

Comments

Please login first before commenting.