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
- -
""".format(str(obj), ent_obj, ent_url, ent_obj, obj.pk) - r = { - "type": ent_obj.lower(), - "label": str(obj), - "id": obj.pk, - "tooltip": tt, - "data": dict(), - } - r["data"]["uri"] = [x.uri for x in obj.uri_set.all()] - r["data"]["notes"] = obj.notes - r["data"]["references"] = obj.references - r["data"]["start_date"] = obj.start_date_written - r["data"]["end_date"] = obj.end_date_written - if ent_obj.lower() != "person": - if obj.kind: - r["data"]["kind"] = obj.kind.name - if ent_obj.lower() == "place": - r["data"]["lat"] = obj.lat - r["data"]["lon"] = obj.lng - if ent_obj.lower() == "person": - r["data"]["profession"] = [x.name for x in obj.profession.all()] - if obj.gender: - r["data"]["gender"] = obj.gender - return r diff --git a/apis_core/apis_entities/serializers_generic.py b/apis_core/apis_entities/serializers_generic.py deleted file mode 100644 index 751feb6b2..000000000 --- a/apis_core/apis_entities/serializers_generic.py +++ /dev/null @@ -1,173 +0,0 @@ -import re - -from django.conf import settings -from django.contrib.contenttypes.models import ContentType -from django.db.models.query import QuerySet -from django.urls import reverse -from rest_framework import serializers - - -base_uri = getattr(settings, "APIS_BASE_URI", "http://apis.info") -if base_uri.endswith("/"): - base_uri = base_uri[:-1] - - -class VocabsSerializer(serializers.Serializer): - id = serializers.IntegerField() - name = serializers.CharField() - label = serializers.CharField() - - -class EntityUriSerializer(serializers.Serializer): - id = serializers.IntegerField() - uri = serializers.URLField() - - -class TextSerializer(serializers.Serializer): - id = serializers.IntegerField() - kind = VocabsSerializer() - text = serializers.CharField() - - -class EntitySerializer(serializers.Serializer): - id = serializers.IntegerField() - url = serializers.SerializerMethodField(method_name="add_url") - uris = EntityUriSerializer(source="uri_set", many=True) - - def add_relations(self, obj): - res = {} - mk = obj.__class__.__name__ - for rel in ContentType.objects.filter( - app_label="apis_relations", model__icontains=mk.lower() - ): - mk2 = re.match(r"{}([A-Za-z]+)".format(mk.lower()), rel.model) - reverse = False - if not mk2: - mk2 = re.match(r"([A-Za-z]+){}".format(mk.lower()), rel.model) - reverse = True - res["{}s".format(mk2.group(1))] = [] - if mk2.group(1).lower() != mk.lower(): - if self._only_published: - rel_qs = ( - getattr(obj, "{}_set".format(rel.model)).all().filter_for_user() - ) - else: - rel_qs = getattr(obj, "{}_set".format(rel.model)).all() - for rel2 in rel_qs: - res["{}s".format(mk2.group(1))].append( - RelationEntitySerializer( - rel2, - own_class=mk, - read_only=True, - context=self.context, - reverse=reverse, - ).data - ) - else: - for t in ["A", "B"]: - for rel2 in ( - getattr(obj, "related_{}{}".format(mk.lower(), t)) - .all() - .filter_for_user() - ): - if t == "A": - ok = "{}B".format(mk.lower()) - reverse = True - else: - ok = "{}A".format(mk.lower()) - reverse = False - res["{}s".format(mk2.group(1))].append( - RelationEntitySerializer( - rel2, - own_class=ok, - read_only=True, - context=self.context, - reverse=reverse, - ).data - ) - return res - - def add_entity_type(self, obj): - return str(obj.__class__.__name__) - - def add_url(self, obj): - url = f"{base_uri}{reverse('GetEntityGenericRoot', kwargs={'pk': obj.pk})}" - return url - - def __init__( - self, *args, depth_ent=1, only_published=True, add_texts=False, **kwargs - ): - super(EntitySerializer, self).__init__(*args, **kwargs) - self._only_published = only_published - if type(self.instance) == QuerySet: - inst = self.instance[0] - else: - inst = self.instance - if inst is None: - return - for f in inst._meta.fields: - field_name = re.search(r"([A-Za-z]+)\'>", str(f.__class__)).group(1) - if field_name in [ - "CharField", - "DateField", - "DateTimeField", - "IntegerField", - "FloatField", - ]: - self.fields[f.name] = getattr(serializers, field_name)() - for f in inst._meta.many_to_many: - if f.name.endswith("relationtype_set"): - continue - self.fields["entity_type"] = serializers.SerializerMethodField( - method_name="add_entity_type" - ) - if depth_ent == 1: - self.fields["relations"] = serializers.SerializerMethodField( - method_name="add_relations" - ) - if add_texts: - self.fields["text"] = TextSerializer(many=True) - - -class RelationEntitySerializer(serializers.Serializer): - id = serializers.IntegerField() - start_date = serializers.DateField() - end_date = serializers.DateField() - start_date_written = serializers.DateField() - end_date_written = serializers.DateField() - relation_type = serializers.SerializerMethodField(method_name="add_relation_label") - - def add_entity(self, obj): - return EntitySerializer( - getattr(obj, "related_{}".format(self.entity_type)), depth_ent=0 - ).data - - def add_relation_label(self, obj): - cm = obj.__class__.__name__ - res_1 = dict() - res_1["id"] = obj.relation_type.pk - res_1["url"] = ( - f"{base_uri}{reverse('apis_core:apis_api:{}relation-detail'.format(cm).lower(), kwargs={'pk': obj.relation_type.pk},)}" - ) - if self.reverse and len(obj.relation_type.label_reverse) > 0: - res_1["label"] = obj.relation_type.label_reverse - elif self.reverse: - res_1["label"] = "({})".format(obj.relation_type.label) - else: - res_1["label"] = obj.relation_type.label - return res_1 - - def __init__(self, *args, own_class=None, reverse=False, **kwargs): - super(RelationEntitySerializer, self).__init__(*args, **kwargs) - self.own_class = own_class - self.reverse = reverse - if self.instance is not None: - for f in self.instance._meta.fields: - if f.name.startswith("related_"): - mk2 = f.name.replace("related_", "") - - if mk2.lower() != own_class.lower(): - self.entity_type = mk2 - self.fields["target"] = serializers.SerializerMethodField( - method_name="add_entity" - ) diff --git a/apis_core/apis_entities/urls.py b/apis_core/apis_entities/urls.py index b8f6608df..78edb5b87 100644 --- a/apis_core/apis_entities/urls.py +++ b/apis_core/apis_entities/urls.py @@ -8,7 +8,6 @@ ) # from .views import ReversionCompareView TODO: add again when import is fixed -from .api_views import GetOrCreateEntity from apis_core.apis_entities.models import AbstractEntity from apis_core.generic.views import List, Create, Delete, Detail from apis_core.apis_entities.views import ( @@ -91,9 +90,4 @@ def to_url(self, value): GenericNetworkEntitiesAutocomplete.as_view(), name="generic_network_entities_autocomplete", ), - path( - "getorcreateentity/", - GetOrCreateEntity.as_view(), - name="GetOrCreateEntity", - ), ] diff --git a/apis_core/urls.py b/apis_core/urls.py index 94d7ed6af..10d381faa 100644 --- a/apis_core/urls.py +++ b/apis_core/urls.py @@ -8,13 +8,6 @@ from django.conf import settings -from apis_core.api_routers import views - -# from apis_core.apis_entities.api_views import ( -# NetJsonViewSet, -# PlaceGeoJsonViewSet, -# ) -from apis_core.utils import caching from apis_core.apis_metainfo.viewsets import UriToObjectViewSet from apis_core.core.views import Dumpdata from apis_core.apis_entities.api_views import GetEntityGeneric @@ -28,20 +21,6 @@ app_name = "apis_core" router = routers.DefaultRouter() -for app_label, model_str in caching.get_all_class_modules_and_names(): - if "_" in app_label: - route_prefix = app_label.split("_")[1] - else: - route_prefix = app_label - try: - router.register( - r"{}/{}".format(route_prefix, model_str.lower()), - views[model_str.lower()], - model_str.lower(), - ) - except Exception: - print("{} not found, skipping".format(model_str.lower())) - # inject the manually created UriToObjectViewSet into the api router router.register(r"metainfo/uritoobject", UriToObjectViewSet, basename="uritoobject")