2017-01-30 26 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