|
1 | | -from flask import Blueprint |
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from flask import Blueprint, make_response |
2 | 6 |
|
3 | 7 | import ckan.plugins.toolkit as tk |
4 | 8 |
|
| 9 | +from ckanext.relationship import utils |
| 10 | + |
| 11 | +BATCH_SIZE_DEFAULT = 20 |
| 12 | + |
5 | 13 |
|
6 | 14 | def get_blueprints(): |
7 | 15 | return [ |
@@ -29,3 +37,61 @@ def relationships_autocomplete(): |
29 | 37 | ), |
30 | 38 | }, |
31 | 39 | ) |
| 40 | + |
| 41 | + |
| 42 | +def _search_packages_page( |
| 43 | + context: dict[str, Any], fq: str, start: int, rows: int |
| 44 | +) -> tuple[list[dict[str, Any]], int]: |
| 45 | + """Searches for packages using the package_search action.""" |
| 46 | + data = { |
| 47 | + "q": "*:*", |
| 48 | + "fq": fq, |
| 49 | + "start": start, |
| 50 | + "rows": rows, |
| 51 | + "include_private": True, |
| 52 | + "sort": "title_string asc, name asc, id asc", |
| 53 | + } |
| 54 | + out = tk.get_action("package_search")({}, data) or {} |
| 55 | + return out.get("results", []), out.get("count", 0) |
| 56 | + |
| 57 | + |
| 58 | +@relationships.route("/relationship/section") |
| 59 | +def related_batch(): |
| 60 | + """Renders a section of related packages.""" |
| 61 | + pkg_id = tk.request.args["pkg_id"] |
| 62 | + object_type = tk.request.args["object_type"] |
| 63 | + relation_type = tk.request.args["relation_type"] |
| 64 | + start = int(tk.request.args.get("start", 0)) |
| 65 | + page_size = int(tk.request.args.get("size", BATCH_SIZE_DEFAULT)) |
| 66 | + |
| 67 | + object_ids = tk.get_action("relationship_relations_ids_list")( |
| 68 | + {}, |
| 69 | + { |
| 70 | + "subject_id": pkg_id, |
| 71 | + "object_entity": "package", |
| 72 | + "object_type": object_type, |
| 73 | + "relation_type": relation_type, |
| 74 | + }, |
| 75 | + ) |
| 76 | + |
| 77 | + if not object_ids: |
| 78 | + return ("", 204) |
| 79 | + |
| 80 | + fq = utils.build_fq_for_object_ids(object_ids) |
| 81 | + packages, total = _search_packages_page({}, fq, start=start, rows=page_size) |
| 82 | + if not packages and start == 0: |
| 83 | + return ("", 204) |
| 84 | + |
| 85 | + html = tk.render( |
| 86 | + "snippets/relationship_related_batch.html", |
| 87 | + extra_vars={ |
| 88 | + "packages": packages, |
| 89 | + "has_more": (start + page_size) < total, |
| 90 | + "next_start": start + page_size, |
| 91 | + "page_size": page_size, |
| 92 | + "pkg_id": pkg_id, |
| 93 | + "object_type": object_type, |
| 94 | + "relation_type": relation_type, |
| 95 | + }, |
| 96 | + ) |
| 97 | + return make_response(html) |
0 commit comments