我正在Flask中编写应用程序,在某些时候我想启动一些进程(快速进程),然后检查服务器上是否有输出。如果有 - 下载它,如果没有 - 显示适当的沟通。
这是我的代码:
import os
import subprocess
import sqlite3
from flask import Flask, render_template, request, redirect, g, send_from_directory
app = Flask(__name__)
app.config.from_object(__name__)
# Config
app.config.update(dict(
DATABASE = os.path.join(app.root_path, 'database/records.db'),
DEBUG = True,
UPLOAD_FOLDER = 'uploads',
OUTPUT_FOLDER = 'outputs',
ALLOWED_EXTENSIONS = set(['txt', 'gro', 'doc', 'docx'])
))
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
def run_calculations(filename):
subprocess.call(['python', os.path.join(app.root_path, 'topologia.py'), 'uploads/' + filename])
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(app.config['DATABASE'])
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/outputs/<filename>')
def calculated_record(filename):
return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
@app.route('/upload', methods = ['GET', 'POST'])
def upload():
with app.app_context():
cur = get_db().cursor()
cur.execute('INSERT INTO records(calculated) VALUES(0)')
file_id = cur.lastrowid
get_db().commit()
file = request.files['file']
if file and allowed_file(file.filename):
input_file = str(file_id) +'.'+file.filename.rsplit('.', 1)[1]
file.save(os.path.join(app.config['UPLOAD_FOLDER'], input_file))
run_calculations(input_file)
output_name = '/outputs/topologia_wynik' + str(file_id) + '.top'
if os.path.isfile(output_name):
return redirect(output_name)
else:
return 'Your file is beeing loaded'
else:
return "Something went wrong, check if your file is in right format ('txt', 'gro', 'doc', 'docx')"
if __name__ == '__main__':
app.run()
我的整个问题出现在这部分代码中:
if os.path.isfile(output_name):
return redirect(output_name)
else:
return 'Your file is beeing loaded'
因为if永远不会......当我删除这部分代码并重定向到输出文件而不检查它一切正常...你知道为什么会这样吗?
答案 0 :(得分:2)
/
开头的原因可能是'/outputs/topologia_wynik' + str(file_id) + '.top'
。这意味着“outputs”文件夹应位于根文件夹下,在您的情况下,它似乎位于服务器工作目录下。
为什么不像输入文件名那样将os.path.join(app.config['OUTPUT_FOLDER'], 'topologia_wynik' + str(file_id) + '.top')
传递给os.path.isfile()
?