diff --git a/apis_core/api_renderers.py b/apis_core/api_renderers.py
deleted file mode 100644
index 298e33e65..000000000
--- a/apis_core/api_renderers.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import re
-from collections import OrderedDict
-
-from rest_framework import renderers
-
-
-class NetJsonRenderer(renderers.JSONRenderer):
- media_type = "application/json"
- format = "json+net"
-
- def render(self, data, media_type=None, renderer_context=None):
- try:
- test = re.search(r"/relations/([^/]+)/", data["results"][0]["url"])
- except IndexError:
- return super().render(
- data, accepted_media_type=media_type, renderer_context=renderer_context
- )
- if test:
- rel = test.group(1)
- for r in data["results"][0].keys():
- if r.startswith("related_"):
- r2 = r.split("_")[1]
- rel2 = re.match("^{}[a-z]*".format(r2), rel)
- if rel2:
- source = r
- elif r.endswith("A"):
- source = r
- elif r.endswith("B"):
- target = r
- rel2 = re.match("^[a-z]*?{}$".format(r2), rel)
- if rel2:
- target = r
- results2 = []
- for d in data["results"]:
- d2 = OrderedDict(
- [
- ("target", v)
- if k == target
- else ("source", v)
- if k == source
- else (k, v)
- for k, v in d.items()
- ]
- )
- results2.append(d2)
- data["results"] = results2
- res3 = super().render(
- data, accepted_media_type=media_type, renderer_context=renderer_context
- )
- return res3
diff --git a/apis_core/api_routers.py b/apis_core/api_routers.py
deleted file mode 100644
index 52403c601..000000000
--- a/apis_core/api_routers.py
+++ /dev/null
@@ -1,409 +0,0 @@
-from functools import reduce
-
-try:
- from apis_ontology.models import *
-except ImportError:
- pass
-from apis_core.apis_metainfo.models import *
-from apis_core.generic.serializers import GenericHyperlinkedModelSerializer
-
-# from django.contrib.contenttypes.models import ContentType
-from django.urls import reverse
-from django.conf import settings
-from rest_framework import pagination, serializers, viewsets
-from rest_framework import renderers
-from rest_framework.response import Response
-
-from drf_spectacular.utils import (
- extend_schema,
- extend_schema_field,
-)
-from drf_spectacular.types import OpenApiTypes
-from django_filters import rest_framework as filters
-from .api_renderers import NetJsonRenderer
-from .apis_relations.models import Triple, Property
-from apis_core.utils import caching
-from apis_core.core.mixins import ListViewObjectFilterMixin
-
-try:
- MAX_AGE = settings.MAX_AGE
-except AttributeError:
- MAX_AGE = 0
-
-
-def deep_get(dictionary, keys, default=None):
- return reduce(
- lambda d, key: d.get(key, default) if isinstance(d, dict) else default,
- keys.split("."),
- dictionary,
- )
-
-
-def create_query_parameters(entity):
- print(entity)
- for f in entity._meta.fields:
- print(f.name, f.__class__.__name__)
-
-
-class CustomPagination(pagination.LimitOffsetPagination):
- def get_paginated_response(self, data):
- return Response(
- {
- "next": self.get_next_link(),
- "previous": self.get_previous_link(),
- "count": self.count,
- "limit": self.limit,
- "offset": self.offset,
- "results": data,
- }
- )
-
-
-class ApisBaseSerializer(serializers.ModelSerializer):
- id = serializers.ReadOnlyField()
- label = serializers.SerializerMethodField(method_name="add_label")
- url = serializers.SerializerMethodField(method_name="add_uri")
-
- @extend_schema_field(OpenApiTypes.INT)
- def add_id(self, obj):
- return obj.pk
-
- @extend_schema_field(OpenApiTypes.STR)
- def add_label(self, obj):
- return str(obj)
-
- @extend_schema_field(OpenApiTypes.URI)
- def add_uri(self, obj):
- return self.context["view"].request.build_absolute_uri(
- reverse(
- "apis:apis_api:{}-detail".format(obj.__class__.__name__.lower()),
- kwargs={"pk": obj.pk},
- )
- )
-
- class Meta:
- fields = ["id", "label", "url"]
-
-
-class EntitySerializer(ApisBaseSerializer):
- type = serializers.SerializerMethodField(method_name="add_type")
-
- def add_type(self, instance):
- return instance.__class__.__name__
-
- class Meta(ApisBaseSerializer.Meta):
- fields = ApisBaseSerializer.Meta.fields + ["type"]
-
-
-class LabelSerializer(ApisBaseSerializer):
- parent_id = serializers.PrimaryKeyRelatedField(
- many=False, source="parent_class_id", read_only=True
- )
-
- @extend_schema_field(OpenApiTypes.INT)
- def add_parent_id(self, obj):
- return obj.parent_class_id
-
- class Meta(ApisBaseSerializer.Meta):
- fields = ApisBaseSerializer.Meta.fields + [
- "parent_id",
- ]
-
-
-class RelatedTripleSerializer(ApisBaseSerializer):
- relation_type = serializers.SerializerMethodField(
- method_name="add_related_property"
- )
- related_entity = serializers.SerializerMethodField(method_name="add_related_entity")
-
- class Meta:
- model = Triple
- fields = ["id", "url", "relation_type", "related_entity"]
-
- def __init__(self, *args, **kwargs):
- self._pk_instance = kwargs.pop("pk_instance")
- super(RelatedTripleSerializer, self).__init__(*args, **kwargs)
-
- def add_related_property(self, triple):
- if triple.subj.pk == self._pk_instance:
-
- class RelatedPropertySerializer(ApisBaseSerializer):
- label = serializers.CharField(source="name_forward")
-
- class Meta:
- model = Property
- fields = ["id", "label", "url"]
-
- elif triple.obj.pk == self._pk_instance:
-
- class RelatedPropertySerializer(ApisBaseSerializer):
- label = serializers.CharField(source="name_reverse")
-
- class Meta:
- model = Property
- fields = ["id", "label", "url"]
-
- else:
- raise Exception(
- "Did not find entity in triple where it is supposed to be. Something must be wrong with the code."
- )
- return RelatedPropertySerializer(triple.prop, context=self.context).data
-
- def add_related_entity(self, triple):
- if triple.subj.pk == self._pk_instance:
- return EntitySerializer(triple.obj, context=self.context).data
- elif triple.obj.pk == self._pk_instance:
- return EntitySerializer(triple.subj, context=self.context).data
- else:
- raise Exception(
- "Did not find entity in triple where it is supposed to be. Something must be wrong with the code."
- )
-
-
-def generic_serializer_creation_factory():
- lst_cont = caching.get_all_contenttype_classes()
- not_allowed_filter_fields = [
- "useradded",
- "parent_class",
- "entity",
- "autofield",
- "metadata",
- ]
- for cont in lst_cont:
- prefetch_rel = []
- select_related = []
- test_search = getattr(settings, cont.__module__.split(".")[1].upper(), False)
- entity_str = str(cont.__name__).replace(" ", "")
- entity = cont
- app_label = cont.__module__.split(".")[1].lower()
- exclude_lst = []
- if app_label == "apis_entities":
- exclude_lst = deep_get(test_search, "{}.api_exclude".format(entity_str), [])
- else:
- set_prem = getattr(settings, cont.__module__.split(".")[1].upper(), {})
- exclude_lst = deep_get(set_prem, "exclude", [])
- exclude_lst.extend(deep_get(set_prem, "{}.exclude".format(entity_str), []))
- entity_field_name_list = []
- for x in entity._meta.get_fields():
- entity_field_name_list.append(x.name)
- exclude_lst_fin = []
- for x in exclude_lst:
- if x in entity_field_name_list:
- exclude_lst_fin.append(x)
- for f in entity._meta.get_fields():
- if f.__class__.__name__ == "ManyToManyField":
- prefetch_rel.append(f.name)
- elif f.__class__.__name__ == "ForeignKey":
- select_related.append(f.name)
-
- class TemplateSerializer(GenericHyperlinkedModelSerializer):
- id = serializers.ReadOnlyField()
- if getattr(settings, "APIS_API_ID_WRITABLE", False):
- id = serializers.IntegerField()
- url = serializers.HyperlinkedIdentityField(
- view_name=f"apis:apis_api:{entity_str.lower()}-detail"
- )
- _entity = entity
- _exclude_lst = exclude_lst_fin
- _app_label = app_label
-
- class Meta:
- model = entity
- exclude = exclude_lst_fin
-
- def add_labels(self, obj):
- return {"id": obj.pk, "label": str(obj)}
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- for f in self._entity._meta.get_fields():
- if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
- f.name
- ).endswith("_set"):
- if f.name in self.fields.keys():
- self.fields.pop(f.name)
- continue
- ck_many = f.__class__.__name__ == "ManyToManyField"
- if f.name in self._exclude_lst:
- continue
- elif f.__class__.__name__ in [
- "ManyToManyField",
- "ForeignKey",
- "InheritanceForeignKey",
- ]:
- pass
- elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
- self.fields[f.name] = LabelSerializer(
- many=ck_many, read_only=True
- )
-
- TemplateSerializer.__name__ = TemplateSerializer.__qualname__ = (
- f"{entity_str.title().replace(' ', '')}Serializer"
- )
-
- class TemplateSerializerRetrieve(TemplateSerializer):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- for f in self._entity._meta.get_fields():
- if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and str(
- f.name
- ).endswith("_set"):
- if f.name in self.fields.keys():
- self.fields.pop(f.name)
- continue
- ck_many = f.__class__.__name__ == "ManyToManyField"
- if f.name in self._exclude_lst:
- continue
- elif f.__class__.__name__ in [
- "ManyToManyField",
- "ForeignKey",
- ]:
- pass
- elif f.__class__.__name__ in ["ManyToManyField", "ForeignKey"]:
- self.fields[f.name] = LabelSerializer(
- many=ck_many, read_only=True
- )
- if len(args) > 0:
- entity = args[0]
- if hasattr(entity, "triple_set_from_subj") or hasattr(
- entity, "triple_set_from_obj"
- ):
- self.fields["relations"] = RelatedTripleSerializer(
- read_only=True,
- source="get_triples",
- many=True,
- pk_instance=entity.pk,
- )
-
- TemplateSerializerRetrieve.__name__ = (
- TemplateSerializerRetrieve.__qualname__
- ) = f"{entity_str.title().replace(' ', '')}DetailSerializer"
-
- allowed_fields_filter = {
- "IntegerField": ["in", "range", "exact"],
- "CharField": ["exact", "icontains", "iregex", "isnull"],
- "DateField": ["year", "lt", "gt", "year__lt", "year__gt", "exact"],
- "PositiveIntegerField": ["in", "range", "exact"],
- "AutoField": ["in", "exact"],
- }
- filterset_dict = {}
- filter_fields = {}
-
- for field in entity._meta.fields + entity._meta.many_to_many:
- if getattr(settings, "APIS_API_EXCLUDE_SETS", False) and "_set" in str(
- field.name.lower()
- ):
- continue
- if (
- field.name.lower() in not_allowed_filter_fields
- or field.name == "tempentityclass_ptr"
- ):
- continue
- elif field.__class__.__name__ in ["ForeignKey", "ManyToManyField"]:
- filter_fields[field.name] = ["exact"]
- if field.__class__.__name__ == "ForeignKey":
- filter_fields[field.name].append("in")
- for f2 in field.related_model._meta.fields:
- if f2.__class__.__name__ in [
- "CharField",
- "DateField",
- "IntegerField",
- "AutoField",
- ]:
- filter_fields[f"{field.name}__{f2.name}"] = (
- allowed_fields_filter[f2.__class__.__name__]
- )
- continue
- if field.__class__.__name__ in allowed_fields_filter.keys():
- filter_fields[field.name] = allowed_fields_filter[
- field.__class__.__name__
- ]
- else:
- filter_fields[field.name] = ["exact"]
- additional_filters = getattr(settings, "APIS_API_ADDITIONAL_FILTERS", False)
- if additional_filters:
- if entity_str in additional_filters.keys():
- for f1 in additional_filters[entity_str]:
- if f1[0] not in filter_fields.keys():
- filter_fields[f1[0]] = f1[1]
-
- class MetaFilter(object):
- model = entity
- fields = filter_fields
-
- filterset_dict["Meta"] = MetaFilter
-
- class TemplateViewSet(ListViewObjectFilterMixin, viewsets.ModelViewSet):
- _select_related = select_related
- _prefetch_rel = prefetch_rel
- pagination_class = CustomPagination
- model = entity
- # filter_backends = (DjangoFilterbackendSpectacular,)
- filter_backends = (filters.DjangoFilterBackend,)
- filterset_fields = filter_fields
- depth = 2
- renderer_classes = (
- renderers.JSONRenderer,
- renderers.BrowsableAPIRenderer,
- NetJsonRenderer,
- )
- _serializer_class = TemplateSerializer
- _serializer_class_retrieve = TemplateSerializerRetrieve
-
- def get_serializer_class(self, *arg, **kwargs):
- if self.action == "list":
- return self._serializer_class
- else:
- return self._serializer_class_retrieve
-
- def get_serializer_context(self):
- context = super(self.__class__, self).get_serializer_context()
- if self.action == "retrieve" and self.model.__name__.lower() == "text":
- cont = {}
- cont["highlight"] = self.request.query_params.get("highlight", None)
- cont["ann_proj_pk"] = self.request.query_params.get(
- "ann_proj_pk", None
- )
- cont["types"] = self.request.query_params.get("types", None)
- cont["users_show"] = self.request.query_params.get(
- "users_show", None
- )
- cont["inline_annotations"] = self.request.query_params.get(
- "inline_annotations", True
- )
- context.update(cont)
- return context
-
- def get_queryset(self):
- if "apis_relations" in str(self.model):
- qs = self.model.objects.filter_for_user()
- else:
- qs = self.model.objects.all()
- if len(self._prefetch_rel) > 0:
- qs = qs.prefetch_related(*self._prefetch_rel)
- if len(self._select_related) > 0:
- qs = qs.select_related(*self._select_related)
- return self.filter_queryset(qs)
-
- @extend_schema(responses=TemplateSerializer(many=True))
- def list_viewset(self, request):
- res = super(self.__class__, self).list(request)
- return res
-
- def dispatch(self, request, *args, **kwargs):
- return super(self.__class__, self).dispatch(request, *args, **kwargs)
-
- TemplateViewSet.__name__ = TemplateViewSet.__qualname__ = (
- f"Generic{entity_str.title().replace(' ', '')}ViewSet"
- )
-
- serializers_dict[TemplateSerializer] = TemplateSerializer
- views[f"{entity_str.lower().replace(' ', '')}"] = TemplateViewSet
-
-
-# TODO: What is this dict 'serializers_dict' used for?
-# I don't find any usage anywhere else and above it gets filled with classes where they are key and value at the same time,
-# which doesn't make sense
-serializers_dict = dict()
-views = dict()
-generic_serializer_creation_factory()
diff --git a/apis_core/apis_entities/api_views.py b/apis_core/apis_entities/api_views.py
index 05fcb20ff..45d65ca2a 100644
--- a/apis_core/apis_entities/api_views.py
+++ b/apis_core/apis_entities/api_views.py
@@ -1,21 +1,8 @@
-import re
-
from django.shortcuts import redirect
-from rest_framework.pagination import PageNumberPagination
-from rest_framework.parsers import FileUploadParser
-from rest_framework.response import Response
-from rest_framework.reverse import reverse_lazy
from rest_framework.views import APIView
from rest_framework.exceptions import NotFound
-from apis_core.apis_metainfo.models import Uri, RootObject
-from apis_core.utils import caching
-
-
-class StandardResultsSetPagination(PageNumberPagination):
- page_size = 25
- page_size_query_param = "page_size"
- max_page_size = 1000
+from apis_core.apis_metainfo.models import RootObject
class GetEntityGeneric(APIView):
@@ -25,43 +12,3 @@ def get(self, request, pk):
return redirect(obj.get_api_detail_endpoint())
except RootObject.DoesNotExist:
raise NotFound
-
-
-class ResolveAbbreviations(APIView):
- parser_classes = (FileUploadParser,)
-
- def put(self, request, filename, format=None):
- return Response(status=204)
-
-
-class GetOrCreateEntity(APIView):
- def get(self, request):
- entity = request.query_params.get("entity2", None)
- uri = request.query_params.get("uri", None)
- if uri and uri.startswith(("http:", "https:")):
- u, _ = Uri.objects.get_or_create(uri=uri)
- ent = u.root_object
- else:
- r1 = re.search(r"^[^<]+", uri)
- r2 = re.search(r"<([^>]+)>", uri)
- q_d = dict()
- q_d["name"] = r1
- if r2:
- for x in r2.group(1).split(";"):
- x2 = x.split("=")
- q_d[x2[0].strip()] = x2[1].strip()
- if entity == "person":
- r1_2 = r1.group(0).split(",")
- if len(r1_2) == 2:
- q_d["first_name"] = r1_2[1].strip()
- q_d["name"] = r1_2[0].strip()
- ent = caching.get_ontology_class_of_name(entity).objects.create(**q_d)
- res = {
- "id": ent.pk,
- "url": reverse_lazy(
- "apis:apis_entities:generic_entities_edit_view",
- request=request,
- kwargs={"pk": ent.pk, "entity": entity},
- ),
- }
- return Response(res)
diff --git a/apis_core/apis_entities/serializers.py b/apis_core/apis_entities/serializers.py
deleted file mode 100644
index 191d1099b..000000000
--- a/apis_core/apis_entities/serializers.py
+++ /dev/null
@@ -1,185 +0,0 @@
-import re
-
-from django.urls import reverse_lazy
-from rest_framework import serializers
-
-
-class BaseEntitySerializer(serializers.HyperlinkedModelSerializer):
- uri_set = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:uri-detail",
- lookup_field="pk",
- many=True,
- read_only=True,
- )
- collection = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:collection-detail",
- lookup_field="pk",
- many=True,
- read_only=True,
- )
- text = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:text-detail",
- lookup_field="pk",
- many=True,
- read_only=True,
- )
-
-
-class GeoJsonSerializer(serializers.BaseSerializer):
- def to_representation(self, obj):
- p_pk = self.context.get("p_pk")
- short = False
- url_r = reverse_lazy(
- "apis:apis_entities:resolve_ambigue_place",
- kwargs={"pk": str(p_pk), "uri": obj["id"][7:]},
- )
- long = False
- if "http://www.w3.org/2003/01/geo/wgs84_pos#long" in obj.keys():
- long = float(
- obj["http://www.w3.org/2003/01/geo/wgs84_pos#long"][0]["value"]
- )
- lat = float(obj["http://www.w3.org/2003/01/geo/wgs84_pos#lat"][0]["value"])
- elif "long" in obj.keys():
- long = float(obj["long"][0]["value"])
- lat = float(obj["lat"][0]["value"])
- short = True
- if long:
- popup = ""
- for k in obj.keys():
- if k == "id" or k == "long" or k == "lat":
- continue
- if not short or k.startswith("http"):
- title = k.split("#")[-1]
- else:
- title = k
- popup += "{}: {}
".format(title, obj[k][0]["value"])
- r = {
- "geometry": {"type": "Point", "coordinates": [long, lat]},
- "type": "Feature",
- "properties": {
- "popupContent": """{}
- Geonames: Select this URI""".format(
- popup, url_r
- )
- },
- "id": url_r,
- }
- return r
- else:
- return ""
-
-
-class GeoJsonSerializerTheme(serializers.BaseSerializer):
- def to_representation(self, obj):
- if obj[0] is None:
- return ""
- url_r = reverse_lazy(
- "apis:apis_core:place-detail", kwargs={"pk": str(obj[0].pk)}
- )
- if obj[0].lng:
- relations = []
- for rel2 in obj[1]:
- if rel2[1] is not None:
- res_str = f"{rel2[1].name} / {rel2[0].name}"
- else:
- res_str = f"{rel2[0].name}"
- if rel2[2] is not None:
- res_str += f" ({rel2[2]}-"
- if rel2[3] is not None:
- if res_str.endswith("-"):
- res_str += f"{rel2[3]})"
- else:
- res_str += f" (-{rel2[3]})"
- if "(" in res_str and not res_str.endswith(")"):
- res_str += ")"
- # relations.append((res_str, rel2[2], rel2[3]))
- relations.append(
- {
- "id": rel2[-1].pk,
- "relation": res_str,
- "start_date": rel2[2],
- "end_date": rel2[3],
- }
- )
- r = {
- "geometry": {"type": "Point", "coordinates": [obj[0].lng, obj[0].lat]},
- "type": "Feature",
- "properties": {
- "name": obj[0].name,
- "uris": [x.uri for x in obj[0].uri_set.all()],
- "kind": obj[0].kind.name
- if obj[0].kind is not None
- else "undefined",
- "url": url_r,
- # "relation_kind": ", ".join([x[0].name for x in obj[1]])
- "relations": relations,
- },
- "id": url_r,
- }
- return r
- else:
- return ""
-
-
-class NetJsonEdgeSerializer(serializers.BaseSerializer):
- def to_representation(self, obj):
- ent_obj = obj.__class__.__name__
- ob_match = re.match(r"([A-Z][a-z]+)([A-Z][a-z]+)$", ent_obj)
- rel_a = "related_" + ob_match.group(1).lower()
- rel_b = "related_" + ob_match.group(2).lower()
- if rel_a == rel_b:
- rel_a += "A"
- rel_b += "B"
- r = {
- "source": getattr(obj, rel_a).pk,
- "target": getattr(obj, rel_b).pk,
- "id": obj.pk,
- "type": "arrow",
- "data": dict(),
- }
- r["data"]["start_date"] = obj.start_date_written
- r["data"]["end_date"] = obj.end_date_written
- r["data"]["relation_type"] = obj.relation_type.name
-
- return r
-
-
-class NetJsonNodeSerializer(serializers.BaseSerializer):
- def to_representation(self, obj):
- ent_obj = obj.__class__.__name__
- ent_url = reverse_lazy(
- "apis:apis_entities:generic_entities_edit_view",
- kwargs={"pk": str(obj.pk), "entity": ent_obj.lower()},
- )
- tt = """
Type | {} |
---|---|
Entity | Link |