Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • AlekSIS/libs/django-iconify
1 result
Show changes
Commits on Source (4)
from django.conf import settings
_prefix = "ICONIFY_"
JSON_ROOT = getattr(settings, f"{_prefix}JSON_ROOT")
......@@ -2,7 +2,10 @@
Documentation: https://docs.iconify.design/types/
"""
from typing import Collection, Dict, Optional
from typing import Collection, Dict, Optional, Union
from typing.io import TextIO
import json
class IconifyOptional:
left: int = 0
......@@ -14,7 +17,7 @@ class IconifyOptional:
h_flip: bool = False
v_flip: bool = False
def _as_dict_optoinal(self) -> dict:
def _as_dict_optional(self) -> dict:
return {
"left": self.left,
"top": self.top,
......@@ -46,9 +49,11 @@ class IconifyIcon(IconifyOptional):
return self
def as_dict(self) -> dict:
return {
res = {
"body": self.body,
}.update(self._as_dict_optional())
}
res.update(self._as_dict_optional())
return res
class IconifyAlias(IconifyOptional):
......@@ -62,9 +67,11 @@ class IconifyAlias(IconifyOptional):
return self
def as_dict(self) -> dict:
return {
res = {
"parent": self.parent,
}.update(self._as_dict_optional())
}
res.update(self._as_dict_optional())
return res
class IconifyJSON(IconifyOptional):
......@@ -103,9 +110,21 @@ class IconifyJSON(IconifyOptional):
return self
@classmethod
def from_file(cls, src_file: Union[str, TextIO] = None, **kwargs) -> "IconifyJSON":
if isinstance(src_file, str):
with open(src_file, "r") as in_file:
src = json.load(in_file)
else:
src = json.load(src_file)
return cls.from_dict(src, **kwargs)
def as_dict(self) -> dict:
return {
res = {
"prefix": self.prefix,
"icons": {name: icon.as_dict() for name, icon in self.icons},
"aliases": {name: alias.as_dict() for name, alias in self.aliases},
}.update(self._as_dict_optional())
"icons": {name: icon.as_dict() for name, icon in self.icons.items()},
"aliases": {name: alias.as_dict() for name, alias in self.aliases.items()},
}
res.update(self._as_dict_optional())
return res
......@@ -3,5 +3,5 @@ from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^(?P<collection>[A-Za-z0-9-]+).(?P<format>js|json)', views.IconifyAPIView.as_view(), name='iconify_api'),
re_path(r'^(?P<collection>[A-Za-z0-9-]+)\.(?P<format_>js(on)?)', views.IconifyJSONView.as_view(), name='iconify_json'),
]
from django.http import HttpRequest, HttpResponse
import json
import os
from django.http import Http404, HttpRequest, HttpResponse, HttpResponseBadRequest
from django.views.generic import View
from .conf import JSON_ROOT
from .types import IconifyJSON
class IconifyJSONView(View):
"""Serve the Iconify icon data retrieval API."""
def get(self, request: HttpRequest, collection: str, format_: str) -> HttpResponse:
"""Retrieve a set of icons using a GET request.
The view supports both JSON and JSONP responses.
"""
# Icon names are passed as comma-separated list
icons = request.GET.get("icons", None)
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", None)
if callback is None:
return HttpResponseBadRequest("The callback argument is mandatory for JSONP.")
# Load icon set through Iconify types
collection_file = os.path.join(JSON_ROOT, "json", f"{collection}.json")
try:
print(icons)
icon_set = IconifyJSON.from_file(collection_file, only=icons)
except FileNotFoundError as exc:
raise Http404(f"Icon collection {collection} not found") from exc
except KeyError as exc:
raise Http404(str(exc)) from exc
class IconifyAPIView(View):
"""Serve the Iconify retrieval API."""
def get(self, request: HttpRequest, collection: str, format: str) -> HttpResponse:
pass
# Get result JSON and form response
res = json.dumps(icon_set.as_dict())
if format_ == "js":
res = f"{callback}({res})"
return HttpResponse(res, content_type="application/json")