diff --git a/dj_iconify/views.py b/dj_iconify/views.py index 710c7bd37cb152fe7b88aadcd8dfee754eb92546..3a94228ab8a95ff15a5994401ae588c4d6764c7d 100644 --- a/dj_iconify/views.py +++ b/dj_iconify/views.py @@ -9,6 +9,32 @@ from .conf import JSON_ROOT from .types import IconifyJSON +class BaseJSONView(View): + def get_data(self, request: HttpRequest) -> dict: + raise NotImplementedError("You must implement this method in your view.") + + def get(self, request: HttpRequest, format_: str = "json", *args, **kwargs) -> HttpResponse: + # For JSONP, the callback name has to be passed + if format_ == "js": + callback = request.GET.get("callback", "SimpleSVG._loaderCallback") + + # Client can request pretty-printing of JSON + if request.GET.get("pretty", "0").lower() in ("1", "true"): + indent = 2 + else: + indent = None + + data = self.get_data(request, *args, **kwargs) + + # Get result JSON and form response + res = json.dumps(data, indent=indent, sort_keys=True) + if format_ == "js": + res = f"{callback}({res})" + return HttpResponse(res, content_type="application/javascript") + else: + return HttpResponse(res, content_type="application/json") + + class ConfigView(View): """Get JavaScript snippet to conifugre Iconify for our API.""" def get(self, request: HttpRequest) -> HttpResponse: @@ -23,9 +49,9 @@ class ConfigView(View): return HttpResponse(f"var IconifyConfig = {config_json}", content_type="text/javascript") -class IconifyJSONView(View): +class IconifyJSONView(BaseJSONView): """Serve the Iconify icon data retrieval API.""" - def get(self, request: HttpRequest, collection: str, format_: str) -> HttpResponse: + def get_data(self, request: HttpRequest, collection: str) -> dict: """Retrieve a set of icons using a GET request. The view supports both JSON and JSONP responses. @@ -36,16 +62,6 @@ class IconifyJSONView(View): if icons is not None: icons = icons.split(",") - # For JSONP, the callback name has to be passed - if format_ == "js": - callback = request.GET.get("callback", "SimpleSVG._loaderCallback") - - # Client can request pretty-printing of JSON - if request.GET.get("pretty", "0").lower() in ("1", "true"): - indent = 2 - else: - indent = None - # Load icon set through Iconify types collection_file = os.path.join(JSON_ROOT, "json", f"{collection}.json") try: @@ -53,13 +69,7 @@ class IconifyJSONView(View): except FileNotFoundError as exc: raise Http404(f"Icon collection {collection} not found") from exc - # Get result JSON and form response - res = json.dumps(icon_set.as_dict(), indent=indent, sort_keys=True) - if format_ == "js": - res = f"{callback}({res})" - return HttpResponse(res, content_type="application/javascript") - else: - return HttpResponse(res, content_type="application/json") + return icon_set.as_dict() class IconifySVGView(View):