File Parsing on the fly in Flask


I recently received some advice on a question regarding an easy to use web-framework to use for a simple project that I am helping a friend with and was suggested to use Flask.

Everything has been working out so far - however I am trying to figure out how to (or if it is possible) to read a file on the fly, and pass the contents of the file into a function that I have.

For instance, I would want to use something like the following:

HTML Side:

<form action="process_file" method=post enctype=multipart/form-data> 
    <input type='file' name='file'> 
    <input type='submit' value="Upload and Process Selected File"> 

I figure that is all I would need on the actual page using HTML, as this would allow me to get the path of the file that I need, so hopefully I would be able to read said-file.

I am unsure as to where to go on the Flask/Python side of things - I'm just looking for a step in the right direction, perhaps reading in two numbers or letters (in the file) and outputting them on the same page?

Flask/Python Side:

@app.route('/process_file', methods=['GET', 'POST'])
def process_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            "Read file and parse the values into an array?"
            "Pass arguments to a Processing function and outputs result into x)"
            return render_template('index.html',answer = x)
            return render_template('index.html',error=1)

I'm not sure if I am headed in the right direction - I just thought someone with more experience with Flask / Python could lead me there.

Edit: I also noticed that Flask seems to play well with jQuery, would using them in combination make processing / file-parsing any simpler?

Thanks everyone.

2/9/2011 8:05:04 PM

Accepted Answer

The documentation on the flask site ( demonstrates how to properly and safely handle file uploads, I would start there. If you wish to parse the file before/instead of saving it, you should be able to use the stream property/attribute on the FileStorage object you're given access to via request.files.

3/27/2013 8:44:44 PM

I am assuming your code is right from flask's perspective. My guess would be that file is a python file-like object. The docs for this tell you everything you need to know about reading and writing files.

As far as parsing goes, well, that depends on the format. My suggestion would be is to write some code up that reads in the file in the format you expect and get your parsing routine solid. then drop then work that into your process_file function.

As far as jquery goes, it's a javascript library. it doesn't care to know what flask is as long as flask speaks http if you are planning on using it for ajax. It wouldn't make the file-parsing any simpler though.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow