2017-01-30 56 views
2

我创建基于在this视频教程使用烧瓶基本上传功能。如何处理用Python-Flask上传的文件?

在“主” Python文件中的代码可以在下面找到。从本质上讲,运行“网页”时,有一个上传功能,一旦你选择文件(S),这些被添加到其创建或在烧瓶程序的其他文件夹旁边已经存在的文件夹。

我的问题是这样的:我要上传到非烧瓶蟒蛇的另一块被立即处理的文件代码 - 应遵循这样做有什么原则呢?例如 - 用python脚本处理CSV文件?在python脚本理论上只是居住在模板文件夹中的HTML文件时,一个合适的文件上传其被激活?

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) 

回答

1

只需编写一个函数来处理您的文件。在你的视图函数中,调用这个新函数。

例如:

def process_file(filename): 
    print filename 

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

如果处理太长,也许你想在后台处理它,请求完成后。 Python有工具来帮助你做到这一点,像python-rqcelery