Reputation: 67
i am writing an application in Flask and at some point I want to start some process (quick process) and then check if there is output on the server. If there is - download it, if not - show approprieate communicate.
Here is my code:
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()
My whole problem is in this part of code:
if os.path.isfile(output_name):
return redirect(output_name)
else:
return 'Your file is beeing loaded'
Because if is never true... When I delete this part of code and redirect to output file without checking it all works fine... Do you have any idea why this happens?
Upvotes: 0
Views: 3693
Reputation: 368
The reason is probably /
in the beginning of '/outputs/topologia_wynik' + str(file_id) + '.top'
. It means "outputs" folder should be under the root folder, and in your case it seems to be under the server working directory.
Why not pass os.path.join(app.config['OUTPUT_FOLDER'], 'topologia_wynik' + str(file_id) + '.top')
to os.path.isfile()
as you did with the input file name?
Upvotes: 2