From 07d79e7a47f67c4f74c5c7d074ca2d02d89256e8 Mon Sep 17 00:00:00 2001 From: Dylan Hillerbrand Date: Thu, 14 Sep 2023 21:50:48 -0400 Subject: [PATCH 1/2] Add CSVRenderer --- .../cantusdata/renderers/csv_renderer.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 app/public/cantusdata/renderers/csv_renderer.py diff --git a/app/public/cantusdata/renderers/csv_renderer.py b/app/public/cantusdata/renderers/csv_renderer.py new file mode 100644 index 00000000..84a24d09 --- /dev/null +++ b/app/public/cantusdata/renderers/csv_renderer.py @@ -0,0 +1,20 @@ +from typing import List +from rest_framework.renderers import BaseRenderer + + +class CSVRenderer(BaseRenderer): + """ + Provides a renderer class which serializes a response to CSV. + The renderer assumes that the response data is a list of dictionaries + with a consistent set of keys (which become the header row in the csv + result). + """ + + media_type = "text/csv" + format = "csv" + + def render(self, data, media_type=None, renderer_context=None): + headers: str = ",".join([str(key) for key in data[0].keys()]) + rows: List[str] = [",".join([str(val) for val in row.values()]) for row in data] + csv_str: str = "\n".join([headers] + rows) + return bytes(csv_str, encoding="utf-8") From 93d66627325b0f16e8f67854e97b2fc5ba89e62f Mon Sep 17 00:00:00 2001 From: Dylan Hillerbrand Date: Thu, 14 Sep 2023 21:51:23 -0400 Subject: [PATCH 2/2] Provide text/csv response to folio_set view --- app/public/cantusdata/views/folio_set.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/app/public/cantusdata/views/folio_set.py b/app/public/cantusdata/views/folio_set.py index 1f842be7..5f5e8feb 100644 --- a/app/public/cantusdata/views/folio_set.py +++ b/app/public/cantusdata/views/folio_set.py @@ -3,7 +3,7 @@ from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.renderers import JSONRenderer -from cantusdata.serializers.search import SearchSerializer +from cantusdata.renderers.csv_renderer import CSVRenderer import solr @@ -17,8 +17,10 @@ class ManuscriptFolioSetView(APIView): - serializer_class = SearchSerializer - renderer_classes = (JSONRenderer,) + renderer_classes = ( + JSONRenderer, + CSVRenderer, + ) def get(self, request, *args, **kwargs): solrconn = solr.SolrConnection(settings.SOLR_SERVER) @@ -65,14 +67,14 @@ def get(self, request, *args, **kwargs): fields="number", score=False, ) - return Response(results) + return Response(results.results) # Otherwise, simply return the given manuscript's folios. composed_request = f'type:"cantusdata_folio" AND manuscript_id:{manuscript_id}' results = solrconn.query( composed_request, sort="number asc", - rows=1000, + rows=10000, fields=FOLIO_FIELDS, score=False, ) - return Response(results) + return Response(results.results)