pavlos163
pavlos163

Reputation: 2890

Flask routing - 404 error

I am trying to create a simple route in my Flask server where just visiting the URL would download a file. Here is my Flask code:

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

However, when I visit localhost:5000/mxl/ or localhost:500/mxl, I get a "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." error. In my command line I see:

127.0.0.1 - - [27/May/2017 02:27:00] "GET /mxl/ HTTP/1.1" 404 -

Why is that happening?

When I run app.url_map I get the following output:

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

Upvotes: 0

Views: 2524

Answers (1)

Tiny.D
Tiny.D

Reputation: 6556

The thing is that Flask has a parameter static_folder, which defaults to the 'static' folder in the root path of the application. And refer to doc to know send_static_file(filename).

Just change your code to:

@app.route('/mxl/')
def mxl():
  return app.send_static_file('piece.mxl')

Or use send_from_directory if you want include the path:

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

it will download the file piece.mxl when you browse http://127.0.0.1:5000/mxl/

Upvotes: 1

Related Questions