pythonpython-3.xcsvfile-storage

Convert werkzeug.datastructures.FileStorage to list of lists for flask backend


Working with flask backend, a csv file is being uploaded to the server with the following html.

<form method="POST" enctype="multipart/form-data" action="/csvUpload">
                  <input type="file" id="myFile" name="filename" accept=".csv">
                  <input type="submit">
 </form>

On the routes.html in flask, we have the following function,

@app.route('/csvUpload', methods=['POST'])
def csvUpload():
    try:
        if request.method == 'POST':
            if request.files:
                uploaded_file = request.files['filename']
                data = uploaded_file.stream.read() # This line uses the same variable and worked fine
                #Convert the FileStorage to list of lists here.
                return data
    except Exception as e:
        traceback.print_exc()
        return "Alas! The code didnt work."

The required output is like the output of a csv.reader(file, 'r'), when reading files from the local system with a static path. The reason for that is that I want to use this csv to update tables in a database attached with the backend.


Solution

  • Try the following method which uses the io.StringIO module:

    @app.route('/csvUpload', methods=['POST'])
    def csvUpload():
        if request.method == 'POST':
            if request.files:
                uploaded_file = request.files['filename']
                data = uploaded_file.stream.read() # This line uses the same variable and worked fine
                #Convert the FileStorage to list of lists here.
    
                stream = io.StringIO(data.decode("UTF8"), newline=None)
                reader = csv.reader(stream)
                for row in reader:
                    print(', '.join(row)) 
    
                return data
    

    Some test data returns the following to the terminal on upload:

    Name, Age
    Kevin, 15
    Perry, 14
    Paul, 30
    

    This code should allow you achieve what you want.