简体   繁体   中英

How can you process a file uploaded with Python-Flask?

I've created a basic upload function using flask, based on the tutorial in this video.

The code in the 'main' python file can be found below. Essentially, when run the 'webpage' has an upload function and once you select file(s), these are added to a folder which is either created or exists already alongside the other folders in the flask programme.

My question is this: I want to upload files to be immediately processed by another block of non-flask python code- what principles should be followed to do this? For example- to process a CSV file with a python script? Can the python script theoretically just be residing in a HTML file in the templates folder which gets activated when a suitable file is uploaded?

import os
from flask import Flask, render_template, request


app = Flask(__name__)

APP__ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    return render_template("upload.html")

@app.route("/upload", methods=['POST'])
def upload():
    target = os.path.join(APP__ROOT, 'data/')
    print(target)

    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("file"):
        print(file)
        filename = file.filename
        destination = "/".join([target, filename])
        print(destination)
        file.save(destination)

    return render_template("complete.html")

if __name__ == "__main__":
    app.run(port=4555, debug=True)

Just write a function to process your file. In your view function, call that new function.

For example:

def process_file(filename):
    print filename

...
file.save(destination)
process_file(destination)

If your processing is too long, maybe you want to process it in background, after the request is done. Python has tools to help you do that, like python-rq or celery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM