'''upload.html'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2 style="color:DodgerBlue;">File Uploader</h2>
<form id = "upload-form" action = "{{ url_for('upload') }}" method="POST"
enctype="multipart/form-data">
<input type = "file" name = "file" accept = "files/*" multiple>
<input type = "submit" value = "submit">
</form>
</body>
</html>
'''app.py'''
import os
from flask import Flask, request, render_template, send_from_directory
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, 'Athena_XML_files/')
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")
@app.route('/run_script')
def run_script():
app.config.from_pyfile("main.py")
return render_template('result.html')
if __name__ == "__main__":
app.run(port=4555, debug=True)
'''complete.html'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>XML files Uploaded</h1>
<ul><br><br>
<h2><strong>Please click to obtain the result</strong></h2><br><br>
<ul class="nav nav-stacked">
<li role="presentation"><a href="{{ url_for('run_script') }}">CLICK
HERE</a></li>
</ul>
</ul>
</body>
</html>
在上传XML文件并单击“单击此处”按钮时,main.py文件应在后台运行,为此我在app.py文件中创建了一个函数来运行main.py文件。
上传效果很好,但是单击按钮时main.py文件不在后台运行。
答案 0 :(得分:0)
我不确定您的想法是否是一个好主意。我发布了一些小型解决方案,但是您应该阅读this文章以获得更好的做法。
1)如果要从flask内部运行外部脚本,则可以使用子进程从命令行运行脚本。
@app.route('/run-script')
def run_script():
result = subprocess.check_output("python main.py", shell=True)
return render_template('results.html', **locals())
2)如果要在后台运行Python代码而没有任何回报,则可以创建一个线程。
from threading import Thread
@app.route('/run-in-background')
def run_in_background():
run_func()
return redirect(url_for('.index'))
def run_func():
data = { 'some': 'data', 'any': 'data' }
thr = Thread(target=run_async_func, args=[app, data])
thr.start()
return thr
def run_async_func(app, data):
with app.app_context():
# Your working code here!
example_module.do_somthing_with(data)
不确定是否有帮助。两种解决方案都可能造成很多混乱。
您应该阅读Flask文档。 app.config.from_pyfile函数从Python代码评估配置数据。这与您的问题完全不同。