graph_public.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import hashlib
  2. import random
  3. import re
  4. import string
  5. import urllib.parse
  6. import dokk.sparql as sparql
  7. from datetime import datetime, timezone
  8. from dokk import settings
  9. from rdflib import Graph, URIRef, Literal
  10. from string import Template
  11. def topic_exists(id):
  12. """
  13. Check if a topic already exists.
  14. :param id: ID of the topic.
  15. """
  16. query = Template("""
  17. PREFIX : <dokk:/>
  18. PREFIX dokk: <https://ontology.dokk.org/>
  19. ASK {
  20. [] dokk:id "$id" ;
  21. a dokk:Topic .
  22. }
  23. """).substitute(id = sparql.escape_literal(id))
  24. response = sparql.query_public(query)
  25. return response['boolean']
  26. def get_topic(id):
  27. """
  28. Retrieve a topic.
  29. :param id: Topic ID.
  30. """
  31. query = Template("""
  32. PREFIX : <dokk:/>
  33. PREFIX dokk: <https://ontology.dokk.org/>
  34. DESCRIBE *
  35. WHERE {
  36. ?s dokk:id "$id" ;
  37. a dokk:Topic .
  38. }
  39. """).substitute(id = sparql.escape_literal(id))
  40. response = sparql.query_public(query)
  41. return response
  42. def list_topics(name):
  43. """
  44. List topics that start with the give name string.
  45. :param name: Search term to match at the beginning of the string.
  46. """
  47. query = Template("""
  48. PREFIX : <dokk:/>
  49. PREFIX dokk: <https://ontology.dokk.org/>
  50. PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
  51. SELECT ?id
  52. WHERE {
  53. [] dokk:id ?id ;
  54. a dokk:Topic .
  55. FILTER STRSTARTS(LCASE(?id), LCASE("$search_term"))
  56. }
  57. ORDER BY ?id
  58. LIMIT 10
  59. """).substitute(search_term = sparql.escape_literal(name))
  60. response = sparql.query_public(query)
  61. return response