apibuilder.py 1.55 KB
Newer Older
Ashish's avatar
Save  
Ashish committed
1 2 3 4
"""
API Builder
Build dynamic API based on the provided SQLAlchemy model
"""
5
from managers import AlchemyModelManager
Ashish's avatar
Save  
Ashish committed
6 7 8 9 10
from viewsets import AlchemyModelViewSet
from rest_framework_nested import routers


class APIModelBuilder(object):
11 12 13 14 15
    def __init__(self,
                 models,
                 base_managers,
                 base_viewsets=None,
                 *args, **kwargs):
Ashish's avatar
Save  
Ashish committed
16
        self.models = models
17 18 19 20 21 22 23 24 25 26

        if not isinstance(base_managers, (tuple, list)):
            base_managers = [base_managers]
        if not isinstance(base_managers, tuple):
            base_managers = tuple(base_managers)
        if base_viewsets is None:
            base_viewsets = (AlchemyModelViewSet,)

        self.base_managers = base_managers
        self.base_viewsets = base_viewsets
Ashish's avatar
Save  
Ashish committed
27 28 29 30 31 32 33 34

    @property
    def urls(self):
        router = routers.SimpleRouter()

        for model in self.models:
            manager = type(
                str('{}Manager'.format(model.__name__)),
35
                self.base_managers + (AlchemyModelManager,),
Ashish's avatar
Save  
Ashish committed
36 37 38 39 40 41
                {
                    'model_class': model,
                }
            )
            viewset = type(
                str('{}ModelViewSet'.format(model.__name__)),
42
                self.base_viewsets,
Ashish's avatar
Save  
Ashish committed
43 44
                {
                    'manager_class': manager,
Ashish's avatar
Save  
Ashish committed
45
                    'paginate_by': 10,
Ashish's avatar
Save  
Ashish committed
46 47 48
                }
            )

Ashish's avatar
Ashish committed
49 50
            router.register('data-api/' + model.__name__.lower() + 's',
                            viewset,
Ashish's avatar
Save  
Ashish committed
51 52 53
                            base_name=model.__name__)

        return router.urls