Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening csv file in Python using Flask

Tags:

python

csv

flask

So, I am trying to open an .csv file in Python using Flask. I copies the code from the Python library, but I go from one error message to the other and I don't know what I am doing wrong. The latest error code I get on the below code is: TypeError: invalid file:

Any ideas what I am doing wrong?

My Python code/Flash route is as follows:

@app.route("/admin", methods=["GET", "POST"])
@login_required
def admin():
    """Configure Admin Screen"""
    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # load csv file with portfolio data
        with open(request.files["portfolios"]) as csvfile:
            portfolios = csv.DictReader(csvfile)

        # load csv file in dictionary
        for row in portfolios:
            print(row['first_name'], row['last_name'])
    else:
        return render_template("admin.html")

My html/Flask code is:

{% extends "layout.html" %}

{% block title %}
    Admin
{% endblock %}

{% block main %}
<h2>Admin Console</h2>
<h3> Upload Portfolio Data</h2>
<form action="{{ url_for('admin') }}" method="post" enctype=multipart/form-data>
    <fieldset>
        <label class="control-label">Select Portfolio Upload File</label>
        <input id="input-1" type="file" class="file" name="portfolios">
        <h3>Upload Security Lists</h2>
        <label class="control-label">Select Security Upload File</label>
        <input id="input-1" type="file" class="file" name="securities">
        <div class="form-group">
            <button class="btn btn-default" type="submit" value = "upload">Upload</button>
        </div>
    </fieldset>
</form>
{% endblock %}
like image 470
Bart Koolhaas Avatar asked Oct 29 '22 07:10

Bart Koolhaas


1 Answers

The file is already open. open takes a string filename and created an open file object, but you don't need to do that because objects in request.files are already open file-like objects.

portfolios = csv.DictReader(request.files['portfolios'])
like image 130
davidism Avatar answered Nov 15 '22 06:11

davidism