connorb08
connorb08

Reputation: 35

Flask static file giving 404

Code in main.py file:

from flask import Flask, render_template, send_from_directory
app = Flask(__name__, static_url_path="")
app._static_folder = "static"

@app.route("/")
def root():
    return app.send_static_file("index.html")

@app.route("/about")
def about():
    return app.send_static_file("about/index.html")

@app.route("/projects")
def projects():
    return app.send_static_file("projects/index.html")

#snip

if __name__ == "__main__":
    app.run(host="0.0.0.0")

When I go to the root directory or the /about directory it works fine, but when I try to go to the /projects directory, I got the error:

Error message:

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

Upvotes: 1

Views: 4479

Answers (1)

Alvin Wan
Alvin Wan

Reputation: 550

There are two possible reasons.

  1. You mis-typed the path. Did you perhaps have a typo in projects (i.e., project) or index.html?
  2. The path doesn't exist. Unlike render_template, app.send_static_file just dies if the path doesn't exist. Since the static_folder is static, then the project page code should exist under static/projects/index.html (and not projects/index.html).

To test if it's a rogue issue, replace the body of the projects view with return 'some string'. If that string doesn't show, then you have a different beast on your hands. If it does, then it's most definitely one of the two bugs I've identified above.

On an un-related note, I would add debug=True to the list of app.run(...) kwargs, to make development more convenient. (The app refreshes whenever there's a file save)

Upvotes: 1

Related Questions