Python 烧瓶路由-404错误

Python 烧瓶路由-404错误,python,flask,routing,Python,Flask,Routing,我正在尝试在Flask服务器中创建一个简单的路由,只要访问URL就可以下载一个文件。这是我的代码: 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']

我正在尝试在Flask服务器中创建一个简单的路由,只要访问URL就可以下载一个文件。这是我的代码:

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时,我得到一个错误消息,因为在服务器上找不到请求的URL。如果您手动输入URL,请检查拼写并重试。错误在我的命令行中,我看到:

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>])

问题是Flask有一个参数static_folder,默认为应用程序根路径中的“static”文件夹。并参考文件了解

只需将代码更改为:

@app.route('/mxl/')
def mxl():
  return app.send_static_file('piece.mxl')
或者,如果要包含路径,请使用:

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.mxlhttp://127.0.0.1:5000/mxl/

我不是烧瓶专家。然而,我在这个网站上尝试了这种方法,它确实奏效了。我假设您希望允许用户在单击按钮后下载某些内容。基本上,您需要make_响应方法来允许您的用户这样做。之前的另一个可能有用的链接app.run,执行:printapp.url\u映射并编辑您的问题以包含输出。我希望浏览器自动下载文件,就像此链接一样:@SuperSaiyan查看更新的问题。谢谢!是否可以确定下载的文件名?现在它只是没有文件扩展名的mxl。我还从浏览器资源中获得一条消息,该消息被解释为文档,但使用MIME类型的应用程序/八位字节流传输:。。为什么会这样?使用“从目录上传”文件夹“piece.mxl”的send_修复了这个问题,如“attachment=True,attachment_filename='piece.mxl'