Skip to content

Commit c624b28

Browse files
committed
api: add route to reverse search files by hash
1 parent 115d6db commit c624b28

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

hhub/urls.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
name="swagger-ui",
3838
),
3939
path("entry/<slug:pk>.json", views.entry_manifest),
40+
path("hash/<slug:hash>", views.search_hash),
4041
path("stats", views.stats),
4142
path("search", views.search_entries),
4243
]

hhub/views.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22

33
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
44
from django.db.models import F, Q
5-
from django.http import JsonResponse
5+
from django.http import JsonResponse, Http404
66

7-
from hhub.models import Entry
7+
from hhub.models import Entry, File
88
from hhub.serializers import EntrySerializer
99

10-
from drf_spectacular.utils import extend_schema
11-
from drf_spectacular.types import OpenApiTypes
10+
from drf_spectacular.utils import extend_schema, OpenApiTypes
1211

1312
from rest_framework.decorators import api_view
1413

@@ -34,6 +33,34 @@ def entry_manifest(request, pk):
3433
return JsonResponse(merged_json_data)
3534

3635

36+
def search_hash(request, hash):
37+
"""
38+
GET /search/<hash>/
39+
-------------------
40+
• 404 if no File rows match *hash*
41+
• JSON list of File rows otherwise (length ≥ 1)
42+
43+
The response body is **always** a list.
44+
Use `safe=False` so `JsonResponse` can emit a top-level JSON array.
45+
"""
46+
qs = File.objects.filter(file_hash=hash).select_related("entry")
47+
48+
if not qs.exists():
49+
raise Http404("No file found with given hash")
50+
51+
payload = [_file_payload(f) for f in qs]
52+
53+
return JsonResponse(payload, safe=False)
54+
55+
56+
def _file_payload(f):
57+
"""Serialize a File instance into a plain-dict."""
58+
return {
59+
"entry_id": f.entry_id,
60+
"name": f.name,
61+
}
62+
63+
3764
def search_entries(request):
3865
"""
3966
Returns every entry matching the conditions given in the query

0 commit comments

Comments
 (0)