如果数据库中找不到数据,Flask 会生成 404 页面

mou*_*ail -1 python flask

我有一个看起来有点像这样的方法:

@app.route("/cms/<path:path>")
def show_page(path):
     page = db.page.get(path=path)
     if page is None:
          return "Page not found", 404
     return str(page)
Run Code Online (Sandbox Code Playgroud)

但是,我想显示我的应用程序默认 404 页面,而不仅仅是这个字符串。

该错误应该与真正的 404 没有区别。我不想渲染任何特定模板,而是为标准 404 渲染任何模板。

有没有办法手动渲染错误页面?我似乎找不到合适的搜索词。

Huy*_*Huy 11

查看Flask 文档,处理 404 错误的主要方法只有 3 种:

  1. 使用render_template(必须有404.html)。

例子:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404
Run Code Online (Sandbox Code Playgroud)
  1. 使用render_template_string(在代码中编写 HTML 模板)。

例子:

from flask import render_template_string
@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template_string('PageNotFound {{ errorCode }}', errorCode='404'), 404
Run Code Online (Sandbox Code Playgroud)
  1. 使用abort:参考文档
abort(404)  # 404 Not Found
abort(Response('Hello World'))
Run Code Online (Sandbox Code Playgroud)