Why do I get a “404 Not Found” error even though the link is on the server?

对着背影说爱祢 提交于 2021-02-07 12:03:19

问题


I'm running a simple test site on PythonAnywhere using Flask. When I run the script, the initial site (index.html) appears, and everything seems fine. However, when I click on any of the links (like signup.html), I get a 404 error:

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

However, the HTML files are all in the templates folder, along with index.html. Why can't they be found on the server?

Here is the Python code that runs the app:

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')

def runit():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

And here is the HTML portion of index.html that holds the link:

<a class="btn btn-lg btn-success" href="signup.html">Sign up</a>

回答1:


You need to create another route for your signup URL, so your main webapp code needs to add a route for '/signup.html', i.e.

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def runit():
    return render_template('index.html')

@app.route('/signup.html')
def signup():
    return render_template('signup.html')

if __name__ == '__main__':
    app.run()

If you want your URLs to be a little cleaner, you can do something like this in your Python:

@app.route('/signup')
def signup():
    return render_template('signup.html')

And change your link code to match.

<a class="btn btn-lg btn-success" href="signup">Sign up</a>

The main Flask documentation has a good overview of routes in their Quickstart guide: http://flask.pocoo.org/docs/quickstart/



来源:https://stackoverflow.com/questions/21807865/why-do-i-get-a-404-not-found-error-even-though-the-link-is-on-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!