Skip to content
Snippets Groups Projects
Verified Commit a6d4eb0f authored by Nik | Klampfradler's avatar Nik | Klampfradler
Browse files

Reformat using black

parent a83d2654
No related branches found
No related tags found
No related merge requests found
...@@ -2,6 +2,5 @@ from django.apps import AppConfig ...@@ -2,6 +2,5 @@ from django.apps import AppConfig
class DjIconifyConfig(AppConfig): class DjIconifyConfig(AppConfig):
name = 'dj_iconify' name = "dj_iconify"
label = 'iconify' label = "iconify"
...@@ -11,6 +11,7 @@ from .util import split_css_unit ...@@ -11,6 +11,7 @@ from .util import split_css_unit
class IconifyOptional: class IconifyOptional:
"""Mixin containing optional attributes all other types can contain.""" """Mixin containing optional attributes all other types can contain."""
left: Optional[int] = None left: Optional[int] = None
top: Optional[int] = None top: Optional[int] = None
width: Optional[int] = None width: Optional[int] = None
...@@ -53,12 +54,15 @@ class IconifyIcon(IconifyOptional): ...@@ -53,12 +54,15 @@ class IconifyIcon(IconifyOptional):
Documentation: https://docs.iconify.design/types/iconify-icon.html Documentation: https://docs.iconify.design/types/iconify-icon.html
""" """
_collection: Optional["IconifyJSON"] _collection: Optional["IconifyJSON"]
_name: str _name: str
body: str body: str
@classmethod @classmethod
def from_dict(cls, name: str, src: dict, collection: Optional["IconifyJSON"] = None) -> "IconifyIcon": def from_dict(
cls, name: str, src: dict, collection: Optional["IconifyJSON"] = None
) -> "IconifyIcon":
self = cls() self = cls()
self.body = src["body"] self.body = src["body"]
self._name = name self._name = name
...@@ -99,7 +103,15 @@ class IconifyIcon(IconifyOptional): ...@@ -99,7 +103,15 @@ class IconifyIcon(IconifyOptional):
else: else:
return 16 return 16
def as_svg(self, color: Optional[str] = None, width: Optional[str] = None, height: Optional[str] = None, rotate: Optional[str] = None, flip: Optional[Union[str, Sequence]] = None, box: bool = False) -> str: def as_svg(
self,
color: Optional[str] = None,
width: Optional[str] = None,
height: Optional[str] = None,
rotate: Optional[str] = None,
flip: Optional[Union[str, Sequence]] = None,
box: bool = False,
) -> str:
"""Generate a full SVG of this icon. """Generate a full SVG of this icon.
Some transformations can be applied by passing arguments: Some transformations can be applied by passing arguments:
...@@ -132,11 +144,13 @@ class IconifyIcon(IconifyOptional): ...@@ -132,11 +144,13 @@ class IconifyIcon(IconifyOptional):
svg_dim_attrs = f'width="{width}" height="{height}"' svg_dim_attrs = f'width="{width}" height="{height}"'
# SVG root element (copied bluntly from example output on api.iconify.design) # SVG root element (copied bluntly from example output on api.iconify.design)
head = ('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' head = (
f'{svg_dim_attrs} ' '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
'preserveAspectRatio="xMidYMid meet" ' f"{svg_dim_attrs} "
f'viewBox="0 0 {orig_width} {orig_height}" ' 'preserveAspectRatio="xMidYMid meet" '
'style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);">') f'viewBox="0 0 {orig_width} {orig_height}" '
'style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);">'
)
foot = "</svg>" foot = "</svg>"
# Build up all transformations, which are added as an SVG group (<g> element) # Build up all transformations, which are added as an SVG group (<g> element)
...@@ -193,13 +207,14 @@ class IconifyIcon(IconifyOptional): ...@@ -193,13 +207,14 @@ class IconifyIcon(IconifyOptional):
# Construct final SVG data # Construct final SVG data
svg = f"{head}{g[0]}{body}{g[1]}{box}{foot}" svg = f"{head}{g[0]}{body}{g[1]}{box}{foot}"
return svg return svg
class IconifyAlias(IconifyOptional): class IconifyAlias(IconifyOptional):
"""Alias for an icon. """Alias for an icon.
Documentation: https://docs.iconify.design/types/iconify-alias.html Documentation: https://docs.iconify.design/types/iconify-alias.html
""" """
_collection: Optional["IconifyJSON"] _collection: Optional["IconifyJSON"]
parent: str parent: str
...@@ -229,6 +244,7 @@ class IconifyInfo(IconifyOptional): ...@@ -229,6 +244,7 @@ class IconifyInfo(IconifyOptional):
No documentation; guessed from the JSON data provided by Iconify. No documentation; guessed from the JSON data provided by Iconify.
""" """
name: str name: str
author: Dict[str, str] # FIXME turn intoreal object author: Dict[str, str] # FIXME turn intoreal object
license_: Dict[str, str] # FIXME turn into real object license_: Dict[str, str] # FIXME turn into real object
...@@ -276,12 +292,13 @@ class IconifyInfo(IconifyOptional): ...@@ -276,12 +292,13 @@ class IconifyInfo(IconifyOptional):
res.update(self._as_dict_optional()) res.update(self._as_dict_optional())
return res return res
class IconifyJSON(IconifyOptional): class IconifyJSON(IconifyOptional):
"""One collection as a whole. """One collection as a whole.
Documentation: https://docs.iconify.design/types/iconify-json.html Documentation: https://docs.iconify.design/types/iconify-json.html
""" """
prefix: str prefix: str
icons: Dict[str, IconifyIcon] icons: Dict[str, IconifyIcon]
aliases: Optional[Dict[str, IconifyAlias]] aliases: Optional[Dict[str, IconifyAlias]]
...@@ -300,7 +317,9 @@ class IconifyJSON(IconifyOptional): ...@@ -300,7 +317,9 @@ class IconifyJSON(IconifyOptional):
return self.aliases[name].get_icon() return self.aliases[name].get_icon()
@classmethod @classmethod
def from_dict(cls, collection: Optional[dict] = None, only: Optional[Collection[str]] = None) -> "IconifyJSON": def from_dict(
cls, collection: Optional[dict] = None, only: Optional[Collection[str]] = None
) -> "IconifyJSON":
"""Construct collection from a dictionary (probably from JSON, originally). """Construct collection from a dictionary (probably from JSON, originally).
If the only parameter is passed a sequence or set, only icons and aliases with If the only parameter is passed a sequence or set, only icons and aliases with
...@@ -332,7 +351,9 @@ class IconifyJSON(IconifyOptional): ...@@ -332,7 +351,9 @@ class IconifyJSON(IconifyOptional):
if alias_dict: if alias_dict:
self.aliases[name] = IconifyAlias.from_dict(alias_dict, collection=self) self.aliases[name] = IconifyAlias.from_dict(alias_dict, collection=self)
# Make sure we also get the real icon to resolve the alias # Make sure we also get the real icon to resolve the alias
self.icons[alias_dict["parent"]] = IconifyIcon.from_dict(alias_dict["parent"], collection["icons"][alias_dict["parent"]], collection=self) self.icons[alias_dict["parent"]] = IconifyIcon.from_dict(
alias_dict["parent"], collection["icons"][alias_dict["parent"]], collection=self
)
continue continue
# If we got here, track the we did not find the icon # If we got here, track the we did not find the icon
......
...@@ -3,9 +3,17 @@ from django.urls import path, re_path ...@@ -3,9 +3,17 @@ from django.urls import path, re_path
from . import views from . import views
urlpatterns = [ urlpatterns = [
path('_config.js', views.ConfigView.as_view(), name='config.js'), path("_config.js", views.ConfigView.as_view(), name="config.js"),
path('collection/', views.CollectionView.as_view(), name='collection'), path("collection/", views.CollectionView.as_view(), name="collection"),
path('collections/', views.CollectionsView.as_view(), name='collections'), path("collections/", views.CollectionsView.as_view(), name="collections"),
re_path(r'^(?P<collection>[A-Za-z0-9-]+)\.(?P<format_>js(on)?)', views.IconifyJSONView.as_view(), name='iconify_json'), re_path(
re_path(r'^(?P<collection>[A-Za-z0-9-]+)/(?P<name>[A-Za-z0-9-]+)\.svg', views.IconifySVGView.as_view(), name='iconify_svg'), r"^(?P<collection>[A-Za-z0-9-]+)\.(?P<format_>js(on)?)",
views.IconifyJSONView.as_view(),
name="iconify_json",
),
re_path(
r"^(?P<collection>[A-Za-z0-9-]+)/(?P<name>[A-Za-z0-9-]+)\.svg",
views.IconifySVGView.as_view(),
name="iconify_svg",
),
] ]
...@@ -4,7 +4,7 @@ import re ...@@ -4,7 +4,7 @@ import re
def split_css_unit(string: str): def split_css_unit(string: str):
"""Split string into value and unit. """Split string into value and unit.
>>> split_css_unit("12px") >>> split_css_unit("12px")
(12, 'px') (12, 'px')
>>> split_css_unit("1.5em") >>> split_css_unit("1.5em")
...@@ -16,6 +16,6 @@ def split_css_unit(string: str): ...@@ -16,6 +16,6 @@ def split_css_unit(string: str):
""" """
_value = re.findall("^[0-9.]+", string) _value = re.findall("^[0-9.]+", string)
value = float(_value[0]) if "." in _value[0] else int(_value[0]) value = float(_value[0]) if "." in _value[0] else int(_value[0])
unit = string[len(_value[0]):] unit = string[len(_value[0]) :]
return value, unit return value, unit
...@@ -25,6 +25,7 @@ class BaseJSONView(View): ...@@ -25,6 +25,7 @@ class BaseJSONView(View):
The URL route has to pass an argument called format_ containing js or json The URL route has to pass an argument called format_ containing js or json
to determine the output format. to determine the output format.
""" """
default_callback: str = "Console.log" default_callback: str = "Console.log"
def get_data(self, request: HttpRequest) -> dict: def get_data(self, request: HttpRequest) -> dict:
...@@ -63,6 +64,7 @@ class ConfigView(View): ...@@ -63,6 +64,7 @@ class ConfigView(View):
This sets the API base URL to the endpoint determined by Django's reverse This sets the API base URL to the endpoint determined by Django's reverse
URL mapper. URL mapper.
""" """
def get(self, request: HttpRequest) -> HttpResponse: def get(self, request: HttpRequest) -> HttpResponse:
# Guess the base URL by reverse-mapping the URL for a fake icon set # Guess the base URL by reverse-mapping the URL for a fake icon set
rev = reverse("iconify_json", kwargs={"collection": "prefix", "format_": "js"}) rev = reverse("iconify_json", kwargs={"collection": "prefix", "format_": "js"})
...@@ -79,10 +81,11 @@ class ConfigView(View): ...@@ -79,10 +81,11 @@ class ConfigView(View):
class CollectionView(BaseJSONView): class CollectionView(BaseJSONView):
"""Retrieve the meta-data for a single collection.""" """Retrieve the meta-data for a single collection."""
def get_data(self, request: HttpRequest) -> dict: def get_data(self, request: HttpRequest) -> dict:
# Collection name is passed in the prefix query parameter # Collection name is passed in the prefix query parameter
collection = request.GET.get("prefix", None) collection = request.GET.get("prefix", None)
if collection is None or not re.match(r'[A-Za-z0-9-]+', collection): if collection is None or not re.match(r"[A-Za-z0-9-]+", collection):
return HttpResponseBadRequest("You must provide a valid prefix name.") return HttpResponseBadRequest("You must provide a valid prefix name.")
# Load icon set through Iconify types # Load icon set through Iconify types
...@@ -98,6 +101,7 @@ class CollectionView(BaseJSONView): ...@@ -98,6 +101,7 @@ class CollectionView(BaseJSONView):
class CollectionsView(BaseJSONView): class CollectionsView(BaseJSONView):
"""Retrieve the available collections with meta-data.""" """Retrieve the available collections with meta-data."""
def get_data(self, request: HttpRequest) -> dict: def get_data(self, request: HttpRequest) -> dict:
# Read the pre-compiled collections list and return it verbatim # Read the pre-compiled collections list and return it verbatim
# FIXME Consider using type models to generate from sources # FIXME Consider using type models to generate from sources
...@@ -109,6 +113,7 @@ class CollectionsView(BaseJSONView): ...@@ -109,6 +113,7 @@ class CollectionsView(BaseJSONView):
class IconifyJSONView(BaseJSONView): class IconifyJSONView(BaseJSONView):
"""Serve the Iconify icon data retrieval API.""" """Serve the Iconify icon data retrieval API."""
default_callback: str = "SimpleSVG._loaderCallback" default_callback: str = "SimpleSVG._loaderCallback"
def get_data(self, request: HttpRequest, collection: str) -> dict: def get_data(self, request: HttpRequest, collection: str) -> dict:
...@@ -132,6 +137,7 @@ class IconifySVGView(View): ...@@ -132,6 +137,7 @@ class IconifySVGView(View):
It serves a single icon as SVG, allowing some transformations. It serves a single icon as SVG, allowing some transformations.
""" """
def get(self, request: HttpRequest, collection: str, name: str) -> HttpResponse: def get(self, request: HttpRequest, collection: str, name: str) -> HttpResponse:
# General retrieval parameters # General retrieval parameters
download = request.GET.get("download", "0").lower() in ("1", "true") download = request.GET.get("download", "0").lower() in ("1", "true")
...@@ -153,7 +159,9 @@ class IconifySVGView(View): ...@@ -153,7 +159,9 @@ class IconifySVGView(View):
# Generate SVG from icon # Generate SVG from icon
icon = icon_set.icons[name] icon = icon_set.icons[name]
icon_svg = icon.as_svg(color=color, width=width, height=height, rotate=rotate, flip=flip, box=box) icon_svg = icon.as_svg(
color=color, width=width, height=height, rotate=rotate, flip=flip, box=box
)
# Form response # Form response
res = HttpResponse(icon_svg, content_type="image/svg+xml") res = HttpResponse(icon_svg, content_type="image/svg+xml")
......
...@@ -2,4 +2,4 @@ from django.apps import AppConfig ...@@ -2,4 +2,4 @@ from django.apps import AppConfig
class DjIconifyServerConfig(AppConfig): class DjIconifyServerConfig(AppConfig):
name = 'dj_iconify_server' name = "dj_iconify_server"
...@@ -11,6 +11,6 @@ import os ...@@ -11,6 +11,6 @@ import os
from django.core.asgi import get_asgi_application from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_iconify_server.settings') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj_iconify_server.settings")
application = get_asgi_application() application = get_asgi_application()
...@@ -3,47 +3,47 @@ from pathlib import Path ...@@ -3,47 +3,47 @@ from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'cv-d4n^*5*$58w474b15pnoqm^fo*10^nv1gg&7q(uaw14o&4p' SECRET_KEY = "cv-d4n^*5*$58w474b15pnoqm^fo*10^nv1gg&7q(uaw14o&4p"
DEBUG = True DEBUG = True
ALLOWED_HOSTS = [] ALLOWED_HOSTS = []
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.staticfiles', "django.contrib.staticfiles",
'django_yarnpkg', "django_yarnpkg",
'dj_iconify.apps.DjIconifyConfig', "dj_iconify.apps.DjIconifyConfig",
'dj_iconify_server.apps.DjIconifyServerConfig', "dj_iconify_server.apps.DjIconifyServerConfig",
] ]
YARN_INSTALLED_APPS = [ YARN_INSTALLED_APPS = [
'@iconify/json', "@iconify/json",
] ]
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', "django.middleware.security.SecurityMiddleware",
'django.middleware.common.CommonMiddleware', "django.middleware.common.CommonMiddleware",
] ]
ROOT_URLCONF = 'dj_iconify_server.urls' ROOT_URLCONF = "dj_iconify_server.urls"
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', "BACKEND": "django.template.backends.django.DjangoTemplates",
'DIRS': [], "DIRS": [],
'APP_DIRS': True, "APP_DIRS": True,
'OPTIONS': { "OPTIONS": {
'context_processors': [ "context_processors": [
'django.template.context_processors.debug', "django.template.context_processors.debug",
'django.template.context_processors.request', "django.template.context_processors.request",
], ],
}, },
}, },
] ]
WSGI_APPLICATION = 'dj_iconify_server.wsgi.application' WSGI_APPLICATION = "dj_iconify_server.wsgi.application"
STATIC_URL = '/static/' STATIC_URL = "/static/"
NODE_MODULES_ROOT = os.path.join(BASE_DIR, 'node_modules') NODE_MODULES_ROOT = os.path.join(BASE_DIR, "node_modules")
ICONIFY_JSON_ROOT = os.path.join(NODE_MODULES_ROOT, "@iconify", "json") ICONIFY_JSON_ROOT = os.path.join(NODE_MODULES_ROOT, "@iconify", "json")
...@@ -2,6 +2,6 @@ from django.views.generic import TemplateView ...@@ -2,6 +2,6 @@ from django.views.generic import TemplateView
from django.urls import include, path from django.urls import include, path
urlpatterns = [ urlpatterns = [
path('icons/', include("dj_iconify.urls")), path("icons/", include("dj_iconify.urls")),
path('test.html', TemplateView.as_view(template_name="test.html")), path("test.html", TemplateView.as_view(template_name="test.html")),
] ]
...@@ -11,6 +11,6 @@ import os ...@@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_iconify_server.settings') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj_iconify_server.settings")
application = get_wsgi_application() application = get_wsgi_application()
...@@ -6,7 +6,7 @@ import sys ...@@ -6,7 +6,7 @@ import sys
def main(): def main():
"""Run administrative tasks.""" """Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_iconify_server.settings') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj_iconify_server.settings")
try: try:
from django.core.management import execute_from_command_line from django.core.management import execute_from_command_line
except ImportError as exc: except ImportError as exc:
...@@ -18,5 +18,5 @@ def main(): ...@@ -18,5 +18,5 @@ def main():
execute_from_command_line(sys.argv) execute_from_command_line(sys.argv)
if __name__ == '__main__': if __name__ == "__main__":
main() main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment