Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from superdjango.exceptions import ViewAlreadyExists
5# Exports
7__all__ = (
8 "API",
9 "api",
10)
12# Classes
15class API(object):
16 """Capture REST API resources.
18 .. code-block:: python
20 # settings.py
21 INSTALLED_APPS = [
22 "superdjango.interfaces.reset.apps.AutoConfig",
23 ]
25 # urls.py
26 from rest_framework import routers
27 from superdjango.interfaces.reset import api
29 router = routers.DefaultRouter()
31 urlpatterns = [
32 # ...
33 path('api/v1/', include(api.get_urls(router))),
34 path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
35 ]
37 """
38 def __init__(self):
39 self._registry = dict()
41 def get_urls(self, router, version=None):
42 """Add discovered APIs to the router.
44 :param router: The Django REST Framework router instance.
45 :type router: BaseType[BaseRouter]
47 :param version: The API version, if any, by which to filter the URLs.
48 :type version: int | str
50 :returns: ``router.urls``
52 """
53 for item in self._registry.values():
54 if version is not None and version != item.version:
55 continue
57 for viewset in item.viewsets:
58 basename = "%s-%s" % (item.basename, viewset.queryset.model.__name__.lower())
59 prefix = "%s/%s" % (item.prefix, viewset.queryset.model.__name__.lower())
61 router.register(prefix, viewset, basename=basename)
63 return router.urls
65 def register(self, app_name, rest_class):
66 """Register an API.
68 :param app_name: The name of the app.
69 :type app_name: str
71 :param rest_class: The REST classs to register.
72 :type rest_class: REST
74 :raise: ViewAlreadyExists
76 """
77 if app_name in self._registry:
78 raise ViewAlreadyExists(app_name + " (REST API)")
80 if rest_class.basename is None:
81 rest_class.basename = "%s-api" % app_name
83 if rest_class.prefix is None:
84 rest_class.prefix = app_name
86 self._registry[app_name] = rest_class
89api = API()