Source code for superdjango.interfaces.rest.interfaces

# Imports

from superdjango.exceptions import ViewAlreadyExists

# Exports

__all__ = (
    "API",
    "api",
)

# Classes


[docs]class API(object): """Capture REST API resources. .. code-block:: python # settings.py INSTALLED_APPS = [ "superdjango.interfaces.reset.apps.AutoConfig", ] # urls.py from rest_framework import routers from superdjango.interfaces.reset import api router = routers.DefaultRouter() urlpatterns = [ # ... path('api/v1/', include(api.get_urls(router))), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] """
[docs] def __init__(self): self._registry = dict()
[docs] def get_urls(self, router, version=None): """Add discovered APIs to the router. :param router: The Django REST Framework router instance. :type router: BaseType[BaseRouter] :param version: The API version, if any, by which to filter the URLs. :type version: int | str :returns: ``router.urls`` """ for item in self._registry.values(): if version is not None and version != item.version: continue for viewset in item.viewsets: basename = "%s-%s" % (item.basename, viewset.queryset.model.__name__.lower()) prefix = "%s/%s" % (item.prefix, viewset.queryset.model.__name__.lower()) router.register(prefix, viewset, basename=basename) return router.urls
[docs] def register(self, app_name, rest_class): """Register an API. :param app_name: The name of the app. :type app_name: str :param rest_class: The REST classs to register. :type rest_class: REST :raise: ViewAlreadyExists """ if app_name in self._registry: raise ViewAlreadyExists(app_name + " (REST API)") if rest_class.basename is None: rest_class.basename = "%s-api" % app_name if rest_class.prefix is None: rest_class.prefix = app_name self._registry[app_name] = rest_class
api = API()