From 4a0ea65d5ece67109cc8468d80cac878536fcca8 Mon Sep 17 00:00:00 2001 From: csae8092 Date: Thu, 16 Nov 2023 12:53:11 +0100 Subject: [PATCH] remove cidoc/ipfi serializer, starting fixing urls --- apis_core/api_routers.py | 98 +------ apis_core/apis_entities/api_renderers.py | 313 +---------------------- apis_core/apis_entities/api_views.py | 19 +- apis_core/apis_entities/urls.py | 10 +- apis_core/apis_labels/urls.py | 12 +- apis_core/apis_metainfo/api_renderers.py | 9 - apis_core/apis_metainfo/urls.py | 6 +- apis_core/apis_relations/urls.py | 2 +- apis_core/apis_tei/tei_urls.py | 10 +- apis_core/urls.py | 182 ++----------- pmb/settings.py | 1 + pmb/urls.py | 7 +- requirements.txt | 2 + 13 files changed, 52 insertions(+), 619 deletions(-) diff --git a/apis_core/api_routers.py b/apis_core/api_routers.py index f6943d4..dd1d1df 100644 --- a/apis_core/api_routers.py +++ b/apis_core/api_routers.py @@ -1,42 +1,18 @@ from functools import reduce -import copy -import importlib -import inspect -import typing - from django.conf import settings -# from django.contrib.contenttypes.models import ContentType from django.urls import reverse from rest_framework import pagination, serializers, viewsets from rest_framework import renderers from rest_framework.response import Response -# from drf_spectacular.contrib.django_filters import ( -# DjangoFilterBackend as DjangoFilterbackendSpectacular, -# ) -from drf_spectacular.utils import ( - extend_schema, - extend_schema_field, - OpenApiParameter, - extend_schema_serializer, -) -from drf_spectacular.types import OpenApiTypes -from django import forms + from django_filters import rest_framework as filters from rest_framework.filters import OrderingFilter from .apis_metainfo.models import TempEntityClass from .api_renderers import NetJsonRenderer -from .apis_relations.models import AbstractRelation from apis_core.helper_functions.ContentType import GetContentTypes - -if "apis_highlighter" in getattr(settings, "INSTALLED_APPS"): - from apis_highlighter.highlighter import highlight_text_new - from apis_highlighter.serializer import annotationSerializer - from apis_highlighter.models import Annotation - - try: MAX_AGE = settings.MAX_AGE except AttributeError: @@ -75,16 +51,12 @@ 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( @@ -93,7 +65,6 @@ def add_uri(self, obj): ) ) - @extend_schema_field(OpenApiTypes.OBJECT) def add_type(self, obj): lst_type = ["kind", "type", "collection_type", "relation_type"] lst_kind = [x for x in obj._meta.fields if x.name in lst_type and "apis_vocabularies" in str(x.related_model)] @@ -139,8 +110,6 @@ class Meta(ApisBaseSerializer.Meta): 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 @@ -158,7 +127,6 @@ class RelationObjectSerializer2(ApisBaseSerializer): relation_type = VocabsBaseSerializer(read_only=True) related_entity = serializers.SerializerMethodField(method_name="add_related_entity") - @extend_schema_field(EntitySerializer) def add_related_entity(self, instance): for at in dir(instance): if at.startswith("related_") and at.endswith("_id") and getattr(instance, at) != self._pk_instance: @@ -172,16 +140,6 @@ def __init__(self, *args, **kwargs): super(RelationObjectSerializer2, self).__init__(*args, **kwargs) -if "apis_highlighter" in getattr(settings, "INSTALLED_APPS"): - - class AnnotationSerializer(serializers.ModelSerializer): - related_object = VocabsBaseSerializer(source="get_related_entity", read_only=True, many=False) - - class Meta: - model = Annotation - fields = ["id", "start", "end", "related_object"] - - def generic_serializer_creation_factory(): lst_cont = GetContentTypes().get_model_classes() not_allowed_filter_fields = [ @@ -491,7 +449,6 @@ def get_queryset(self): qs = qs.select_related(*self._select_related) return qs - @extend_schema(responses=TemplateSerializer(many=True)) def list_viewset(self, request): res = super(self.__class__, self).list(request) return res @@ -499,56 +456,9 @@ def list_viewset(self, request): def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) - if entity_str.lower() == "text": - - @extend_schema( - parameters=[ - OpenApiParameter( - name="highlight", - description="Whether to add annotations or not, defaults to true", - type=OpenApiTypes.BOOL, - ), - OpenApiParameter( - name="inline_annotations", - description="Whether to add html5 mark tags for annotations to the text, defaults to false", - type=OpenApiTypes.BOOL, - ), - OpenApiParameter( - name="ann_proj_pk", - description="PK of the annotation project to use for annotations", - type=OpenApiTypes.INT, - ), - OpenApiParameter( - name="types", - description="Content type pks of annotation types to show. E.g. PersonPlace relations (comma sperated list)", - type=OpenApiTypes.STR, - ), - OpenApiParameter( - name="users_show", - description="Filter annotations for users. PKs of users, comma seperated list", - type=OpenApiTypes.STR, - ), - ], - responses={200: TemplateSerializerRetrieve}, - ) - def retrieve(self, request, pk=None): - res = super(self.__class__, self).retrieve(request, pk=pk) - return res - - else: - - @extend_schema( - parameters=[ - OpenApiParameter( - name="include_relations", - description="Whether to include serialization of relations or not. Usefull to avoid timeouts on big objects. Defaults to true", - type=OpenApiTypes.BOOL, - ) - ] - ) - def retrieve(self, request, pk=None): - res = super(self.__class__, self).retrieve(request, pk=pk) - return res + def retrieve(self, request, pk=None): + res = super(self.__class__, self).retrieve(request, pk=pk) + return res TemplateViewSet.__name__ = TemplateViewSet.__qualname__ = f"Generic{entity_str.title().replace(' ', '')}ViewSet" diff --git a/apis_core/apis_entities/api_renderers.py b/apis_core/apis_entities/api_renderers.py index 84d722f..c9444f3 100644 --- a/apis_core/apis_entities/api_renderers.py +++ b/apis_core/apis_entities/api_renderers.py @@ -1,29 +1,7 @@ -import json -import os -import pickle -from datetime import date - from django.conf import settings -from django.core.serializers.json import DjangoJSONEncoder -from django.utils import timezone -from rdflib import XSD, Graph, Literal, Namespace, URIRef, ConjunctiveGraph, OWL -from rdflib.namespace import DCTERMS, VOID -from rdflib import plugin -from rdflib.store import Store -from rdflib.void import generateVoID from rest_framework import renderers from apis_core.apis_tei.tei import TeiEntCreator -from .api_mappings.cidoc_mapping import m_person, m_place, m_work, m_institution - -try: - from webpage.metadata import PROJECT_METADATA -except ImportError: - try: - from webpage.utils import PROJECT_METADATA - except ImportError: - PROJECT_METADATA = getattr(settings, "PROJECT_DEFAULT_MD") - base_uri = getattr(settings, "APIS_BASE_URI", "http://apis.info") if base_uri.endswith("/"): @@ -38,293 +16,4 @@ class EntityToTEI(renderers.BaseRenderer): def render(self, data, media_type=None, renderer_context=None): tei_doc = TeiEntCreator(data) - return tei_doc.serialize_full_doc() - - -class EntityToCIDOC(renderers.BaseRenderer): - - media_type = "text/rdf" - - ent_func = { - "Person": m_person, - "Place": m_place, - "Work": m_work, - "Institution": m_institution, - } - - def render( - self, - data1, - media_type=None, - renderer_context=None, - format_1=None, - binary=False, - store=False, - named_graph=None, - provenance=False, - ): - if isinstance(data1, dict): - data1 = [data1] - if format_1 is not None: - self.format = format_1 - cidoc = Namespace("http://www.cidoc-crm.org/cidoc-crm/") - geo = Namespace("http://www.opengis.net/ont/geosparql#") - frbroo = Namespace("http://iflastandards.info/ns/fr/frbr/frbroo#") - if not store: - store = plugin.get("Memory", Store)() - if named_graph: - uri_entities = URIRef(named_graph) - else: - uri_entities = URIRef(f"{base_uri}/entities#") - g = Graph(store, identifier=uri_entities) - g.bind("cidoc", cidoc, override=False) - g.bind("geo", geo, override=False) - g.bind("owl", OWL, override=False) - g.bind("frbroo", frbroo, override=False) - ns = {"cidoc": cidoc, "geo": geo, "frbroo": frbroo} - if type(data1) == list: - for data in data1: - g, ent = self.ent_func[data["entity_type"]]( - g, ns, data, drill_down=True - ) - elif type(data1) == str: - directory = os.fsencode(data1) - for fn in os.listdir(directory): - with open(os.path.join(directory, fn), "rb") as inf: - data2 = pickle.load(inf) - for data in data2: - g, ent = self.ent_func[data["entity_type"]]( - g, ns, data, drill_down=True - ) - if provenance: - g_prov = Graph( - store, identifier=URIRef("https://omnipot.acdh.oeaw.ac.at/provenance") - ) - g_prov.bind("dct", DCTERMS, override=False) - g_prov.bind("void", VOID, override=False) - g_prov.add( - ( - uri_entities, - DCTERMS.title, - Literal(PROJECT_METADATA["title"], lang=lang), - ) - ) - g_prov.add( - ( - uri_entities, - DCTERMS.description, - Literal(PROJECT_METADATA["description"], lang=lang), - ) - ) - g_prov.add( - ( - uri_entities, - DCTERMS.creator, - Literal(PROJECT_METADATA["author"], lang=lang), - ) - ) - g_prov.add( - (uri_entities, DCTERMS.publisher, Literal("ACDH-OeAW", lang=lang)) - ) - g_prov.add((uri_entities, DCTERMS.source, URIRef(base_uri))) - g_prov.add( - ( - uri_entities, - DCTERMS.created, - Literal(str(date.today()), datatype=XSD.date), - ) - ) - g_prov, g = generateVoID(g, dataset=uri_entities, res=g_prov) - g_all = ConjunctiveGraph(store=store) - if binary: - return g_all, store - return g_all.serialize(format=self.format.split("+")[-1]) - - -class EntityToCIDOCXML(EntityToCIDOC): - - format = "rdf+xml" - - -class EntityToCIDOCN3(EntityToCIDOC): - - format = "rdf+n3" - - -class EntityToCIDOCNQUADS(EntityToCIDOC): - - format = "rdf+nquads" - - -class EntityToCIDOCTURTLE(EntityToCIDOC): - - format = "rdf+turtle" - - -class EntityToProsopogrAPhI(renderers.BaseRenderer): - - media_type = "text/json+prosop" - format = "json+prosop" - - def render(self, data, media_type=None, renderer_context=None): - factoids = [] - fact_settings = getattr(settings, "PROSOPOGRAPHI_API", None) - stmt_temp = "Stmt{}_{}" - f = {"@id": "apis_{}_{}".format(data["entity_type"].lower(), data["id"])} - f[data["entity_type"].lower()] = {"@id": str(data["id"])} - f["source"] = { - "@id": PROJECT_METADATA["title"], - "label": "{} export".format(PROJECT_METADATA["title"]), - } - f["createdBy"] = "{} export".format(PROJECT_METADATA["title"]) - f["createdWhen"] = timezone.now() - stmt_count = 1 - stmts = [] - f[data["entity_type"].lower()]["uris"] = [] - for u in data["uris"]: - f[data["entity_type"].lower()]["uris"].append(u["uri"]) - if data["entity_type"].lower() == "person": - s = { - "@id": stmt_temp.format(data["id"], stmt_count), - "name": "{}, {}".format(data["name"], data["first_name"]), - } - stmts.append(s) - stmt_count += 1 - if "end_date" in data.keys(): - if data["end_date"] is not None and data["end_date"] != "": - s = { - "@id": stmt_temp.format(data["id"], stmt_count), - "date": { - "sortdate": data["end_date"], - "label": data["end_date_written"], - }, - "role": {"label": "stirbt"}, - } - stmts.append(s) - stmt_count += 1 - if "start_date" in data.keys(): - if data["start_date"] is not None and data["start_date"] != "": - s = { - "@id": stmt_temp.format(data["id"], stmt_count), - "date": { - "sortdate": data["start_date"], - "label": data["start_date_written"], - }, - "role": {"label": "geboren"}, - } - stmts.append(s) - stmt_count += 1 - if "gender" in data.keys(): - if data["gender"] is not None and data["gender"] != "": - s = { - "@id": stmt_temp.format(data["id"], stmt_count), - "statmentType": [{"label": data["gender"]}], - "role": {"uri": "bio-crm:gender", "label": "gender"}, - } - stmts.append(s) - stmt_count += 1 - if "profession" in data.keys(): - if len(data["profession"]) > 0: - s = { - "@id": stmt_temp.format(data["id"], stmt_count), - "role": {"label": "profession"}, - "statementType": [], - } - for p in data["profession"]: - s2 = { - "uri": "apis_profession_type:{}".format(p["id"]), - "label": p["label"], - } - s["statementType"].append(s2) - stmts.append(s) - stmt_count += 1 - f["statements"] = stmts - factoids.append(f) - facts = [] - facts_ind = {} - if "relations" in data.keys(): - for ent in data["relations"].keys(): - for rel_1 in data["relations"][ent]: - s = { - "@id": "Stmt{}_rel_{}".format(data["id"], rel_1["id"]), - "role": { - "label": rel_1["relation_type"]["label"], - "url": rel_1["relation_type"]["url"], - }, - } - if "start_date" in rel_1.keys(): - if rel_1["start_date"] != "": - s["date"] = { - "sortdate": rel_1["start_date"], - "label": rel_1["start_date_written"], - } - if rel_1["end_date_written"] != "": - s["date"]["label"] += "-{}".format( - rel_1["end_date_written"] - ) - ext_stc = False - t1 = { - "uri": "{}/api2/entity/{}".format( - base_uri, rel_1["target"]["id"] - ), - "label": rel_1["target"]["name"], - } - if fact_settings is not None: - if ent in fact_settings.keys(): - if ( - rel_1["relation_type"]["label"] - in fact_settings[ent].keys() - ): - s[ - fact_settings[ent][rel_1["relation_type"]["label"]] - ] = t1 - ext_stc = True - if not ext_stc: - s["statementType"] = [t1] - try: - if len(rel_1["annotation"]) > 0: - s["statementContent"] = rel_1["annotation"][0]["text"] - except TypeError: - pass - # stct = { - # "@id": "Annotation_{}".format(rel_1["annotation"][0]["id"]), - # "label": rel_1["annotation"][0]["text"] - # } - # if "statementContent" in s.keys(): - # s["statementContent"].append(stct) - # else: - # s["statementContent"] = [stct,] - if len(rel_1["revisions"]) > 0: - user_1 = rel_1["revisions"][0]["user_created"] - date_1 = rel_1["revisions"][0]["date_created"].strftime( - "%Y-%m-%d" - ) - rev_id = rel_1["revisions"][0]["id"] - if "{}_{}".format(user_1, date_1) not in facts_ind.keys(): - facts_ind["{}_{}".format(user_1, date_1)] = len(factoids) - s3 = { - "person": factoids[0]["person"], - "@id": "{}_{}".format(factoids[0]["@id"], len(stmts)), - "source": { - "@id": "APIS", - "label": "APIS highlighter annotations rev. {}".format( - rev_id - ), - }, - "createdBy": user_1, - "createdWhen": date_1, - "statements": [s], - } - factoids.append(s3) - else: - factoids[facts_ind["{}_{}".format(user_1, date_1)]][ - "statements" - ].append(s) - factoids[facts_ind["{}_{}".format(user_1, date_1)]][ - "source" - ]["label"] += " / {}".format(rev_id) - else: - factoids[0]["statements"].append(s) - return json.dumps( - {"factoids": factoids}, sort_keys=True, indent=1, cls=DjangoJSONEncoder - ) + return tei_doc.serialize_full_doc() \ No newline at end of file diff --git a/apis_core/apis_entities/api_views.py b/apis_core/apis_entities/api_views.py index ef766aa..dd565ad 100644 --- a/apis_core/apis_entities/api_views.py +++ b/apis_core/apis_entities/api_views.py @@ -6,7 +6,7 @@ import requests from django.conf import settings -from django.db.models import Q, Prefetch +from django.db.models import Q from django.http import Http404 from django.shortcuts import redirect from django.urls import reverse @@ -22,7 +22,6 @@ from rest_framework.settings import api_settings from rest_framework.views import APIView -from apis_core.apis_metainfo.api_renderers import PaginatedCSVRenderer from apis_core.apis_metainfo.models import TempEntityClass, Uri from apis_core.apis_relations.models import ( PersonPlace, @@ -40,11 +39,6 @@ from apis_core.helper_functions.stanbolQueries import find_loc from .api_renderers import ( EntityToTEI, - EntityToCIDOCXML, - EntityToProsopogrAPhI, - EntityToCIDOCN3, - EntityToCIDOCNQUADS, - EntityToCIDOCTURTLE, ) from .models import Event, Institution, Person, Place, Work, AbstractEntity from .serializers import ( @@ -76,11 +70,6 @@ class GetEntityGeneric(GenericAPIView): queryset = TempEntityClass.objects.all() renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + ( EntityToTEI, - EntityToCIDOCXML, - EntityToProsopogrAPhI, - EntityToCIDOCN3, - EntityToCIDOCNQUADS, - EntityToCIDOCTURTLE, ) if getattr(settings, "APIS_RENDERERS", None) is not None: rend_add = tuple() @@ -183,9 +172,9 @@ class PlaceViewSet(viewsets.ModelViewSet): depth = 2 filter_fields = ("name", "kind__name", "collection__name") search_fields = ("name",) - renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + ( - PaginatedCSVRenderer, - ) + # renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + ( + # PaginatedCSVRenderer, + # ) class EventViewSet(viewsets.ModelViewSet): diff --git a/apis_core/apis_entities/urls.py b/apis_core/apis_entities/urls.py index f00c4e4..bd428b6 100644 --- a/apis_core/apis_entities/urls.py +++ b/apis_core/apis_entities/urls.py @@ -13,12 +13,12 @@ urlpatterns = [ url( - r"^entity/(?P[a-z]+)/(?P[0-9]+)/edit$", + r"^entity/(?P[a-z]+)//edit$", views2.GenericEntitiesEditView.as_view(), name="generic_entities_edit_view", ), url( - r"^entity/(?P[a-z]+)/(?P[0-9]+)/detail$", + r"^entity/(?P[a-z]+)//detail$", detail_views.GenericEntitiesDetailView.as_view(), name="generic_entities_detail_view", ), @@ -28,7 +28,7 @@ name="generic_entities_create_view", ), url( - r"^entity/(?P[a-z]+)/(?P[0-9]+)/delete$", + r"^entity/(?P[a-z]+)//delete$", views2.GenericEntitiesDeleteView.as_view(), name="generic_entities_delete_view", ), @@ -68,13 +68,13 @@ name="generic_network_entities_autocomplete", ), # TODO __sresch__ : This seems unused. Remove it once sure - # url(r'^detail/work/(?P[0-9]+)$', + # url(r'^detail/work/$', # detail_views.WorkDetailView.as_view(), name='work_detail'), url(r"^place/geojson/$", views.getGeoJson, name="getGeoJson"), url(r"^place/geojson/list/$", views.getGeoJsonList, name="getGeoJsonList"), url(r"^place/network/list/$", views.getNetJsonList, name="getNetJsonList"), url( - r"^resolve/place/(?P[0-9]+)/(?P.+)$", + r"^resolve/place//(?P.+)$", views.resolve_ambigue_place, name="resolve_ambigue_place", ), diff --git a/apis_core/apis_labels/urls.py b/apis_core/apis_labels/urls.py index 138cd41..d74251a 100644 --- a/apis_core/apis_labels/urls.py +++ b/apis_core/apis_labels/urls.py @@ -1,13 +1,13 @@ # -*- coding: utf-8 -*- -from django.conf.urls import url +from django.urls import path from . import views -app_name = 'apis_labels' +app_name = "apis_labels" urlpatterns = [ -url(r'^list/$', views.LabelListView.as_view(), name='label_list'), -url(r'^create/$', views.label_create, name='label_create'), -url(r'^edit/(?P[0-9]+)$', views.label_edit, name='label_edit'), -url(r'^delete/(?P[0-9]+)$', views.LabelDelete.as_view(), name='label_delete'), + path("list/", views.LabelListView.as_view(), name="label_list"), + path("create/", views.label_create, name="label_create"), + path("edit/", views.label_edit, name="label_edit"), + path("delete/", views.LabelDelete.as_view(), name="label_delete"), ] diff --git a/apis_core/apis_metainfo/api_renderers.py b/apis_core/apis_metainfo/api_renderers.py index edeb260..b70d22d 100644 --- a/apis_core/apis_metainfo/api_renderers.py +++ b/apis_core/apis_metainfo/api_renderers.py @@ -1,6 +1,5 @@ from django.template.loader import render_to_string from rest_framework import renderers -from rest_framework_csv.renderers import CSVRenderer class TEIBaseRenderer(renderers.BaseRenderer): @@ -12,11 +11,3 @@ def render(self, data, media_type=None, renderer_context=None): return data - -class PaginatedCSVRenderer(CSVRenderer): - results_field = 'results' - - def render(self, data, *args, **kwargs): - if not isinstance(data, list): - data = data.get(self.results_field, []) - return super(PaginatedCSVRenderer, self).render(data, *args, **kwargs) diff --git a/apis_core/apis_metainfo/urls.py b/apis_core/apis_metainfo/urls.py index cffe85b..7771fd7 100644 --- a/apis_core/apis_metainfo/urls.py +++ b/apis_core/apis_metainfo/urls.py @@ -11,7 +11,7 @@ name='uri_browse' ), url( - r'^uri/detail/(?P[0-9]+)$', + r'^uri/detail/$', views.UriDetailView.as_view(), name='uri_detail' ), @@ -21,12 +21,12 @@ name='uri_create' ), url( - r'^uri/edit/(?P[0-9]+)$', + r'^uri/edit/$', views.UriUpdate.as_view(), name='uri_edit' ), url( - r'^uri/delete/(?P[0-9]+)$', + r'^uri/delete/$', views.UriDelete.as_view(), name='uri_delete'), ] diff --git a/apis_core/apis_relations/urls.py b/apis_core/apis_relations/urls.py index 04e68c5..4eb1d8d 100644 --- a/apis_core/apis_relations/urls.py +++ b/apis_core/apis_relations/urls.py @@ -13,7 +13,7 @@ ), url(r'^(?P[a-z]+)/list/$', rel_views.GenericRelationView.as_view(), name='generic_relations_list'), - url(r'^(?P[a-z]+)/(?P[0-9]+)/detail$', + url(r'^(?P[a-z]+)//detail$', rel_views.GenericRelationDetailView.as_view(), name='generic_relations_detail_view'), ] diff --git a/apis_core/apis_tei/tei_urls.py b/apis_core/apis_tei/tei_urls.py index 3cd5edc..4186587 100644 --- a/apis_core/apis_tei/tei_urls.py +++ b/apis_core/apis_tei/tei_urls.py @@ -18,28 +18,28 @@ name='tei_completer_autocomplete' ), url( - r'^person/(?P[0-9]+)$', + r'^person/$', views.person_as_tei, name='person_as_tei' ), url( - r'^place/(?P[0-9]+)$', + r'^place/$', views.place_as_tei, name='place_as_tei' ), url( - r'^org/(?P[0-9]+)$', + r'^org/$', views.org_as_tei, name='org_as_tei' ), url( - r'^institution/(?P[0-9]+)$', + r'^institution/$', views.org_as_tei, name='org_as_tei' ), url( - r'^work/(?P[0-9]+)$', + r'^work/$', views.work_as_tei, name='work_as_tei' ), diff --git a/apis_core/urls.py b/apis_core/urls.py index b1ebc15..91c074c 100644 --- a/apis_core/urls.py +++ b/apis_core/urls.py @@ -1,19 +1,9 @@ -from django.conf import settings -from django.conf.urls import include, url -from django.contrib import admin -from django.contrib.auth.decorators import login_required -from django.contrib.contenttypes.models import ContentType from django.urls import path -from django.views.static import serve -from django_filters.rest_framework import DjangoFilterBackend -from rest_framework import response, schemas +from django.conf.urls import include from rest_framework import routers -from rest_framework.decorators import api_view, renderer_classes -from rest_framework.schemas import get_schema_view from apis_core.api_routers import views from apis_core.apis_entities.api_views import ( - NetJsonViewSet, PlaceGeoJsonViewSet, ) from apis_core.apis_vocabularies.api_views import UserViewSet @@ -30,7 +20,7 @@ route_prefix = app_label try: router.register( - r"{}/{}".format(route_prefix, model_str.lower()), + "{}/{}".format(route_prefix, model_str.lower()), views[model_str.lower()], model_str.lower(), ) @@ -38,172 +28,32 @@ print("{} not found, skipping".format(model_str.lower())) -if "apis_highlighter" in settings.INSTALLED_APPS: - from apis_highlighter.api_views import ( - HighlighterProjectViewSet, - HighlighterTextHighViewSet, - HighlighterMenuEntryViewSet, - HighlighterHighlightTextViewSet, - HighlighterVocabularyAPIViewSet, - HighlighterAnnotationViewSet, - ) - - router.register(r"HLProjects", HighlighterProjectViewSet) - router.register(r"HLTextHigh", HighlighterTextHighViewSet) - router.register(r"HLMenuEntry", HighlighterMenuEntryViewSet) - # router.register( - # r"HLTextHighlighter", HighlighterHighlightTextViewSet, "HLTextHighlighter" - # ) - # router.register(r"HLVocabularyAPI", HighlighterVocabularyAPIViewSet) - router.register(r"HLAnnotation", HighlighterAnnotationViewSet) - -router.register(r"users", UserViewSet) -router.register(r"GeoJsonPlace", PlaceGeoJsonViewSet, "PlaceGeoJson") -# router.register(r"NetJson", NetJsonViewSet, "NetJson") - - -from rest_framework import permissions - -# from drf_yasg.views import get_schema_view as get_schema_view2 -# from drf_yasg import openapi -from drf_spectacular.views import ( - SpectacularAPIView, - SpectacularSwaggerView, - SpectacularRedocView, -) - - -# schema_view2 = get_schema_view2( -# openapi.Info( -# title="APIS API", -# default_version='v1', -# description="Hyperlinked API of the APIS Framework", -# terms_of_service="https://www.google.com/policies/terms/", -# contact=openapi.Contact(email="matthias.schloegl@oeaw.ac.at"), -# license=openapi.License(name="MIT"), -# ), -# public=True, -# permission_classes=(permissions.AllowAny,), -# ) - -# class APISSchemaGenerator(OpenAPISchemaGenerator): -# info = "APIS test" -# title = "APIS_API v2" - -# def __init__(self, *args, **kwargs): -# super(APISSchemaGenerator, self).__init__(*args, **kwargs) - - -# class SchemaViewSwagger(schema_view2): -# generator_class = APISSchemaGenerator - -# def get_filter_parameters(self, filter_backend): -# if isinstance(filter_backend, DjangoFilterBackend): -# result = super(SchemaViewSwagger, self).get_filter_parameters(filter_backend) -# for param in result: -# if not param.get('description', ''): -# param.description = "Filter the returned list by {field_name}".format(field_name=param.name) - -# return result - -# return NotHandled - -# def get_operation(self, operation_keys): -# super(SchemaViewSwagger, self).get_operation(operation_keys) - -# def __init__(self, *args, **kwargs): -# super(SchemaViewSwagger, self).__init__(*args, **kwargs) - - -def build_apis_mock_request(method, path, view, original_request, **kwargs): - # default mock request - request = build_mock_request(method, path, view, original_request, **kwargs) - # the added wagtail magic - request.router = router - return request +router.register("users", UserViewSet) +router.register("GeoJsonPlace", PlaceGeoJsonViewSet, "PlaceGeoJson") urlpatterns = [ - url(r"^admin/", admin.site.urls), - path('beacon/', beacon, name="beacon"), - # url(r'^swagger(?P\.json|\.yaml)$', SchemaViewSwagger.without_ui(cache_timeout=-1), name='schema-json'), - # url(r'^swagger/$', SchemaViewSwagger.with_ui('swagger', cache_timeout=-1), name='schema-swagger-ui'), - # url(r'^redoc/$', SchemaViewSwagger.with_ui('redoc', cache_timeout=-1), name='schema-redoc'), - path("swagger/schema/", SpectacularAPIView.as_view(), name="schema"), - # Optional UI: + path("beacon/", beacon, name="beacon"), + path("labels/", include("apis_core.apis_labels.urls", namespace="apis_labels")), + path("tei/", include("apis_core.apis_tei.tei_urls", namespace="apis_tei")), path( - "swagger/schema/swagger-ui/", - SpectacularSwaggerView.as_view(url_name="apis_core:schema"), - name="swagger-ui", + "entities/", include("apis_core.apis_entities.urls", namespace="apis_entities") ), + path("openrefine/", include("apis_core.openrefine.urls", namespace="openrefine")), path( - "swagger/schema/redoc/", - SpectacularRedocView.as_view(url_name="apis_core:schema"), - name="redoc", - ), - url(r"labels/", include("apis_core.apis_labels.urls", namespace="apis_labels")), - url(r"tei/", include("apis_core.apis_tei.tei_urls", namespace="apis_tei")), - url( - r"entities/", include("apis_core.apis_entities.urls", namespace="apis_entities") - ), - url(r"visuals/", include("apis_core.apis_vis.urls", namespace="apis_visuals")), - path('openrefine/', include('apis_core.openrefine.urls', namespace='openrefine')), - url( - r"relations/", + "relations/", include("apis_core.apis_relations.urls", namespace="apis_relations"), ), - url( - r"vocabularies/", + path( + "vocabularies/", include("apis_core.apis_vocabularies.urls", namespace="apis_vocabularies"), ), - url( - r"metainfo/", + path( + "metainfo/", include("apis_core.apis_metainfo.urls", namespace="apis_metainfo"), ), - url( - r"metainfo-ac/", + path( + "metainfo-ac/", include("apis_core.apis_metainfo.dal_urls", namespace="apis_metainfo-ac"), ), - # url(r'^autocomplete/', include('autocomplete_light.urls')), - url( - r"^api/", include((router.urls, "apis_core"), namespace="apis_api") - ), # routers do not support namespaces out of the box - # path('openapi-2', schema_view), - # path('openapi-api', get_schema_view( - # title="APIS", - # description="APIS API schema definition", - # urlconf='apis_core.apis_entities.api_urls', - # ), name='openapi-schema-api'), - url(r"^api2/", include("apis_core.apis_entities.api_urls", namespace="apis_api2")), - url(r"^api-auth/", include("rest_framework.urls", namespace="rest_framework")), - # url(r'^api-schema/', schema_view), - url(r"^apis-vis/", include("apis_core.apis_vis.urls", namespace="apis_vis")), - url( - r"^docs/(?P.*)$", - login_required(serve), - {"document_root": "apis-core/docs/_build/html"}, - "docs", - ), - # url(r'^docs/', include('sphinxdoc.urls')), - # url(r'^accounts/', include('registration.backends.simple.urls')), ] - -if "apis_highlighter" in settings.INSTALLED_APPS: - urlpatterns.append( - url(r"highlighter/", include("apis_highlighter.urls", namespace="highlighter")) - ) - -if "apis_fulltext_download" in settings.INSTALLED_APPS: - - urlpatterns.append( - url( - r"fulltext_download/", - include("apis_fulltext_download.urls", namespace="apis_fulltext_download"), - ) - ) - -if settings.DEBUG: - if "debug_toolbar" in settings.INSTALLED_APPS: - import debug_toolbar - - urlpatterns = [url(r"^__debug__/", include(debug_toolbar.urls))] + urlpatterns diff --git a/pmb/settings.py b/pmb/settings.py index 5f11fe9..f318b8c 100644 --- a/pmb/settings.py +++ b/pmb/settings.py @@ -29,6 +29,7 @@ "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", + "browsing", "apis_core.apis_entities", "apis_core.apis_metainfo", "apis_core.apis_relations", diff --git a/pmb/urls.py b/pmb/urls.py index 3812689..e44c80c 100644 --- a/pmb/urls.py +++ b/pmb/urls.py @@ -2,7 +2,8 @@ from django.urls import path, include urlpatterns = [ - path('admin/', admin.site.urls), - path('arche/', include('archemd.urls')), - path('', include('dumper.urls')), + path("apis/", include("apis_core.urls", namespace="apis")), + path("admin/", admin.site.urls), + path("arche/", include("archemd.urls")), + path("", include("dumper.urls")), ] diff --git a/requirements.txt b/requirements.txt index d676b64..7610bf0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ acdh-id-reconciler>=0.2,<1 +acdh-tei-pyutils>=0.34,<1 Django>4.1,<5 django-admin-csvexport django-autocomplete-light @@ -11,4 +12,5 @@ celery>=5.2.7,<6 pandas psycopg2 pyocclient==0.6 +PyYAML>=6.0.1,<7 rdflib