-1

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

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

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

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

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

4

1 回答 1

2

查看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
  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
  1. 使用abort:参考文档
abort(404)  # 404 Not Found
abort(Response('Hello World'))
于 2021-09-18T12:24:55.723 回答