我正在尝试在我的Flask服务器中创建一个简单的路由,只需访问该URL即可下载文件。这是我的Flask代码:
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/')
app = Flask(__name__, static_url_path=UPLOAD_FOLDER)
Bootstrap(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.debug = False
app.secret_key = 'notverysecret'
@app.route('/', methods=['GET', 'POST'])
def index():
...
return render_template('index.html', request="POST", pitches=pitches)
@app.route('/mxl/')
def mxl():
return app.send_static_file(UPLOAD_FOLDER + 'piece.mxl')
if __name__ == "__main__":
app.run()
但是,当我访问localhost:5000/mxl/
或localhost:500/mxl
时,我收到“在服务器上找不到请求的网址。如果您手动输入了网址,请检查您的拼写然后重试。”错误。在我的命令行中,我看到:
127.0.0.1 - - [27/May/2017 02:27:00] "GET /mxl/ HTTP/1.1" 404 -
为什么会这样?
当我运行app.url_map
时,我得到以下输出:
Map([<Rule '/mxl/' (HEAD, OPTIONS, GET) -> mxl>,
<Rule '/' (HEAD, POST, OPTIONS, GET) -> index>,
<Rule '/home/myusername/guitartab/guitartab/static//bootstrap/<filename>' (HEAD, OPTIONS, GET) -> bootstrap.static>,
<Rule '/home/myusername/guitartab/guitartab/static//<filename>' (HEAD, OPTIONS, GET) -> static>])
答案 0 :(得分:1)
问题是Flask有一个参数static_folder
,它默认为应用程序根路径中的'static'文件夹。并参考doc以了解send_static_file(filename)。
只需将您的代码更改为:
@app.route('/mxl/')
def mxl():
return app.send_static_file('piece.mxl')
如果您想要包含路径,请使用send_from_directory:
from flask import send_from_directory
@app.route('/mxl/')
def mxl():
print("test")
#return app.send_static_file('piece.mxl')
return send_from_directory(UPLOAD_FOLDER,'piece.mxl')
当您浏览piece.mxl
http://127.0.0.1:5000/mxl/