使用 flask 时出现 404 Not found 错误

404 Not found error while using flask

我正在 python 使用 Flask 学习 Web 开发。该代码没有显示任何错误,但是当我 运行 它时,浏览器显示错误 - 404 未找到。 代码:

from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/admin/')
def hello_admin():
   return 'Hello Admin'
@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest
@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))
if __name__ == '__main__':
   app.run(debug=True)

Chrome 中的输出: 未找到 在服务器上找不到请求的 URL。如果您手动输入 URL,请检查拼写并重试

来自Flask documentation

An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply:

  • If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.
  • If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised

IMO,你可能会遇到第二种情况。