Skip to content

Commit

Permalink
Split code into utils file
Browse files Browse the repository at this point in the history
  • Loading branch information
jamclar committed Sep 1, 2023
1 parent a94ba95 commit ae4df95
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 30 deletions.
36 changes: 8 additions & 28 deletions nvsvocprez/routes/collection_pages.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Render the Collection Endpoints."""
import json
from bs4 import BeautifulSoup

from itertools import groupby
from pathlib import Path
from typing import AnyStr, Literal, Optional, Tuple
Expand All @@ -19,6 +19,7 @@
from .page_configs import DATA_URI, ORDS_ENDPOINT_URL, SYSTEM_URI, acc_dep_map
from .profiles import void, nvs, skos, dd, vocpub, dcat, sdo
from .utils import (
RelatedItem,
cache_return,
exists_triple,
get_alt_profiles,
Expand Down Expand Up @@ -647,7 +648,7 @@ def _render_nvs_or_profile_html(self):
"collection_label": None,
"definition": None,
"date": None,
"altLabels": [],
"altLabels": [],
"profile_properties": [],
"annotation": [],
"agent": [],
Expand Down Expand Up @@ -800,30 +801,7 @@ def clean_prop_list_labels(prop_list):

context["logged_in_user"] = get_user_status(self.request)

class RelatedItem:
"""Hold related items and provide functionality for sorting and grouping."""

def __init__(self, object_html, predicate_html=""):
"""Initialise the HTML attributes."""
self.object_html = object_html

self.predicate_html = predicate_html if predicate_html else ""

@property
def collection(self):
"""Return the collection or empty string for an item."""
result = re.search(r'(/">)([A-Z]+\w\w)(</a>)', self.object_html)
return result.group(2) if result and len(result.groups()) == 3 else ""

@property
def description(self):
"""Parse the description from an item."""
return BeautifulSoup(self.object_html, features="html.parser")("td")[-1].text

def __lt__(self, other):
"""Utility method needed for sorting items."""
return self.description.lower() < other.description.lower()


# Create Instances of Items
contexts = [
RelatedItem(predicate_html=item.predicate_html, object_html=item.object_html) for item in context["related"]
Expand All @@ -836,19 +814,21 @@ def __lt__(self, other):
last_pairing = c.predicate_html
ddict[last_pairing].append(c)


# Sort each group of items alphabetically.
context["related"] = {k: sorted(v) for k, v in ddict.items()}

def _sort_by(item: list):
"""Utility function to dictate sorting logic."""
result = re.search(r"(<td>)(.+?)(</td>)", item[1][0].object_html)
return len(item[1]), result.group(2).lower() if result else ""
return len(item[1]), item[0], result.group(2).lower() if result else ""

for k in context["related"].keys():
sorted_items = sorted(context["related"][k], key=lambda item: item.collection)
grouped = {item: list(lst) for item, lst in groupby(sorted_items, key=lambda item: item.collection)}
context["related"][k] = {k: v for k, v in sorted(grouped.items(), key=_sort_by)}



alt_label_query = """
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT * WHERE {
Expand Down
27 changes: 26 additions & 1 deletion nvsvocprez/routes/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
from pathlib import Path
import requests
from pyldapi.data import RDF_MEDIATYPES

import re
from pyldapi.profile import Profile
from utilities import config
from bs4 import BeautifulSoup


api_home_dir = Path(__file__).parent
Expand Down Expand Up @@ -373,3 +374,27 @@ def get_collection_query(profile: Profile, instance_uri: str, ontologies: Dict):
}}
"""
return query


class RelatedItem:
"""Hold related items and provide functionality for sorting and grouping."""

def __init__(self, object_html, predicate_html=""):
"""Initialise the HTML attributes."""
self.object_html = object_html
self.predicate_html = predicate_html if predicate_html else ""

@property
def collection(self):
"""Return the collection or empty string for an item."""
result = re.search(r'(/">)([A-Z]+\w\w)(</a>)', self.object_html)
return result.group(2) if result and len(result.groups()) == 3 else ""

@property
def description(self):
"""Parse the description from an item."""
return BeautifulSoup(self.object_html, features="html.parser")("td")[-1].text

def __lt__(self, other):
"""Utility method needed for sorting items."""
return self.description.lower() < other.description.lower()
3 changes: 2 additions & 1 deletion nvsvocprez/view/templates/concept.html
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ <h2>{{ prefLabel }}</h2>
</tr>
{% else %}
<tr class="group-header header">
<th colspan="3" style="color:#007dbb;font-size:12px;">
<th></th>
<th colspan="3" style="color:#007dbb;font-size:12px;cursor: pointer">
{{ "{} {} - ({})".format(k, alt_labels[k], vi|length) }}
<span class="toggle-icon">[+]</span>
</th>
Expand Down

0 comments on commit ae4df95

Please sign in to comment.