我有一个关于url_for Unable to open files in python flask- 404 not found的问题。但被标记为重复。
我的要求非常简单。在主页面中创建指向输出文件夹中的文件的href链接。我在SO中尝试了几乎所有的线程,答案似乎对我不起作用。我是python的新手。请帮忙。以下是我试过的示例代码
from flask import Flask, redirect, url_for,send_from_directory
app = Flask(__name__)
@app.route('/main')
def index():
print 'test'
return '''<a href="{{ url_for('uploaded_file', filename='a.txt') }}">Open file</a>'''
@app.route('/out/<filename>')
def uploaded_file(filename):
print filename
return send_from_directory('./out/',
filename)
@app.route('/out/<filename>')
def uploaded_file2(filename):
print filename
return './out/'+filename
if __name__ == '__main__':
app.run(debug = True)
答案 0 :(得分:0)
你的app目录结构应该是这样的,所以这段代码可行。如果在out文件夹中找不到文件名,那么您将看到“url not found”:
app/
app.py
static/
out/
a.txt
templates/
index.html
from flask import Flask, render_template, redirect, url_for,send_from_directory
app = Flask(__name__)
app.config.update(
UPLOAD_FOLDER = "static/out/"
)
@app.route('/main')
def index():
print ('test')
return render_template('index.html')
@app.route('/out/<filename>')
def uploaded_file(filename):
print (filename)
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
@app.route('/showfilepath/<filename>')
def uploaded_file2(filename):
print (filename)
return app.config["UPLOAD_FOLDER"] + filename
if __name__ == '__main__':
app.run(debug = True)
# index.html
<a href="{{url_for('uploaded_file', filename='a.txt')}}">open file</a>
# a.txt
hey there ...