From 9385152fa1f1142465cced8872938b8ece7755f4 Mon Sep 17 00:00:00 2001 From: Juan Date: Mon, 7 Dec 2020 13:06:31 -0400 Subject: [PATCH] #53 #54 Created CSV Renderer to present serialized data in CSV format. --- src/cvservices/renderers.py | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/cvservices/renderers.py b/src/cvservices/renderers.py index b0dd3ee..e8e64ba 100644 --- a/src/cvservices/renderers.py +++ b/src/cvservices/renderers.py @@ -1,3 +1,8 @@ +import csv +from ctypes import Union +from io import BytesIO, StringIO +from typing import Union, Dict, List, KeysView + from rest_framework import renderers @@ -10,8 +15,31 @@ def render(self, data, media_type=None, renderer_context=None): class CSVRenderer(renderers.BaseRenderer): - media_type = 'text/csv' - format = 'csv' + media_type: str = 'text/csv' + format: str = 'csv' - def render(self, data, media_type=None, renderer_context=None): - return "This is CSV DATA" + def render(self, data: Union[Dict, List[Dict]], media_type: str = None, renderer_context=None) -> str: + """ + Receives an already serialized object/list of objects and converts it to a csv file. + :param data: An individual or a list of serialized controlled vocabulary objects. + :param media_type: The media type of the request. + :param renderer_context: The renderer context. + :return: A CSV rendition of the serialized controlled vocabulary. + """ + if data is None: + return '' + + if not isinstance(data, list): + data = [data] + + # Create string buffer to store hold the csv file content + csv_buffer: StringIO = StringIO() + # Get the fieldnames from the first object in the data + fieldnames: KeysView = data[0].keys() + # Create a CSV writer with the string buffer + csv_writer: csv.DictWriter = csv.DictWriter(csv_buffer, fieldnames=fieldnames) + # Write the headers and data to the CSV writer + csv_writer.writeheader() + csv_writer.writerows(data) + # Return the contents of the writer + return csv_buffer.getvalue()