Python 检查文件是否存在但实际文件确实存在
我正在用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'
因为这个条件永远不成立……当我删除这部分代码,直接跳转到输出文件而不检查时,一切都正常……你知道这是为什么吗?
1 个回答
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()
,就像你对输入文件名那样呢?