J
J
Jekson2020-02-18 11:39:54
Django
Jekson, 2020-02-18 11:39:54

Choosing the code implementation logic when generating instances from a csv file?

There is a task to parse a csv file and, based on the data received, create instances in the database. On the back of DRF on the front of React.
The peculiarity is that the processing of the file is not completely hidden. The logic is this:
There is a file download button. The file is loaded, validated, but nothing is immediately created in the database. A window appears with a list of parsed data (like a table) and in this window a new button confirm by clicking on which the query is already going to the database.
What I did now:
1. Created a class for uploading a file (Upload button)

class FileUploadView(APIView):
    parser_classes = ( MultiPartParser, FormParser)

    def put(self, request, format=None):
        if 'file' not in request.data:
            raise ParseError("Empty content")
        f = request.data['file']
        filename = f.name
        file_ext = filename[-4:]
        if file_ext == '.csv':
            file = default_storage.save(filename, f)
            r = csv_file_parser(file)
            status = 204
        else:
            status = 406
            r = "File format error"
        return Response({'response': r}, status=status)


The csv_file_parser function is called in the class, the result of which is json containing all the parsed data.

def csv_file_parser(file):

    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        line_count = 1
        result_dict= {}
        for row in reader:
            for key, value in row.items():
                if not value:
                    raise ParseError('Missing value in file. Check the {} line'.format(line_count))
            new = {line_count: row}
            result_dict.update(new)
            line_count += 1
        return json.dumps(result_dict)


The code is working (if you have ideas for its optimization - welcome :) ). What I can't figure out is how do I fit the Confirm button into the code. What and how to use for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-18
@Lepilov

You are now sending sparged data from the back to the front. Well, build a confirmation form on the front according to this data. After clicking on Confirm, send this data directly as json again to the back. But already on another endpoint, which will accept this data and do something in the database.
PS Instead of a file extension, it's better to get it like this: . Well, or check to do so . filename[-4:]os.path.splitext(filename)if filename.endswith('.csv')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question