Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"> 
</form> 

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)
        else:
            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.

like image 355
Rion Williams Avatar asked Dec 22 '22 18:12

Rion Williams


1 Answers

The documentation on the flask site (http://flask.pocoo.org/docs/patterns/fileuploads/) 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.

like image 145
Philip Southam Avatar answered Dec 28 '22 10:12

Philip Southam