繁体   English   中英

虽然文件DO存在,但Python检查文件是否存在无效

[英]Python check if file exists doesnt work although the file DO exists

我正在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'

因为如果永远不是真的...当我删除这部分代码并重定向到输出文件而不检查它一切正常...你知道为什么会发生这种情况吗?

原因可能是/'/outputs/topologia_wynik' + str(file_id) + '.top'的开头。 这意味着“outputs”文件夹应位于根文件夹下,在您的情况下,它似乎位于服务器工作目录下。

为什么不像输入文件名那样将os.path.join(app.config['OUTPUT_FOLDER'], 'topologia_wynik' + str(file_id) + '.top')传递给os.path.isfile()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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