diff --git a/orp/config/urls.py b/orp/config/urls.py index 1c8161c..11130d6 100644 --- a/orp/config/urls.py +++ b/orp/config/urls.py @@ -12,6 +12,11 @@ path("", orp_search_views.search, name="search"), # If we choose to have a start page with green button, this is it: # path("", core_views.home, name="home"), + path( + "download_csv/", + orp_search_views.download_search_csv, + name="download_csv", + ), path("details/", orp_search_views.details, name="details"), path("healthcheck/", core_views.health_check, name="healthcheck"), path( diff --git a/orp/orp_search/templates/orp.html b/orp/orp_search/templates/orp.html index ad65da8..41008b1 100644 --- a/orp/orp_search/templates/orp.html +++ b/orp/orp_search/templates/orp.html @@ -180,9 +180,23 @@


- Download search results as CSV + Download search results as CSV file

+ + diff --git a/orp/orp_search/views.py b/orp/orp_search/views.py index eb6631e..bec5e02 100644 --- a/orp/orp_search/views.py +++ b/orp/orp_search/views.py @@ -1,5 +1,8 @@ +import csv import logging +import pandas as pd + from orp_search.public_gateway import PublicGateway, SearchDocumentConfig from django.conf import settings @@ -52,6 +55,45 @@ def details(request: HttpRequest, id) -> HttpResponse: return render(request, template_name="details.html", context=context) +@require_http_methods(["GET"]) +def download_search_csv(request: HttpRequest) -> HttpResponse: + search_terms = request.GET.get("query", "") + document_type_terms = request.GET.get("document_type", "") + publisher_terms = request.GET.getlist("publisher", None) + sort_by = request.GET.get("sort", None) + + config = SearchDocumentConfig( + search_terms, document_type_terms, dummy=True + ) + + if publisher_terms: + config.publisher_terms = publisher_terms + + if sort_by: + config.sort_by = sort_by + + public_gateway = PublicGateway() + search_results = public_gateway.search(config) + + # Convert search_results JSON object to DataFrame + # (for demonstration purposes) + search_results_df = pd.DataFrame(search_results) + + response = HttpResponse(content_type="text/csv") + response["Content-Disposition"] = ( + 'attachment; filename="search_results.csv"' + ) + + # Write the DataFrame to the response + writer = csv.writer(response) + writer.writerow(search_results_df.columns) # Write the header + + for _, row in search_results_df.iterrows(): + writer.writerow(row) + + return response + + @require_http_methods(["GET"]) def search(request: HttpRequest) -> HttpResponse: """Search view. @@ -117,7 +159,6 @@ def search(request: HttpRequest) -> HttpResponse: if sort_by: config.sort_by = sort_by - # Check if the response is cached public_gateway = PublicGateway() search_results = public_gateway.search(config) context["results_count_total"] = len(search_results)