gpt4 book ai didi

python - Flask:重定向不存在的 URL

转载 作者:太空狗 更新时间:2023-10-30 00:35:28 25 4
gpt4 key购买 nike

我得到了执行以下操作的说明:修改 app.py 文件,以便我的网站响应所有可能的 URL(又名不存在的扩展名,如“/jobs”,这意味着如果输入了无效的 URL,它将重定向到主页 index.html 页面。这是我的 app.py 的副本,关于如何执行此操作有什么想法吗?

from flask import Flask, render_template  #NEW IMPORT!!

app = Flask(__name__) #This is creating a new Flask object

#decorator that links...

@app.route('/') #This is the main URL
def index():
return render_template("index.html", title="Welcome",name="home")

@app.route('/photo')
def photo():
return render_template("photo.html", title="Home", name="photo-home")

@app.route('/about')
def photoAbout():
return render_template("photo/about.html", title="About", name="about")

@app.route('/contact')
def photoContact():
return render_template("photo/contact.html", title="Contact", name="contact")

@app.route('/resume')
def photoResume():
return render_template("photo/resume.html", title="Resume", name="resume")

if __name__ == '__main__':
app.run(debug=True) #debug=True is optional

最佳答案

我认为您正在寻找的可能只是错误处理。 Flask 文档有一个部分展示了如何做 error handling .

但从那里总结要点:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404

您有一个应用程序实例,因此您可以将其添加到您的代码中。很明显,只要出现 404 或页面不存在,就会呈现 404.html

假设您正在使用 jinja 模板,404.html的内容可能是:

{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<h1>Page Not Found</h1>
<p>What you were looking for is just not there.
<p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}

这需要一个基础模板(这里是layout.html)。假设现在您不想使用 jinja 模板,只需将其用作 404.html:

  <h1>Page Not Found</h1>
<p>What you were looking for is just not there.
<p><a href="{{ url_for('index') }}">go somewhere nice</a>

在您的情况下,因为您想查看主页(index.html 可能):

@app.errorhandler(404)
def page_not_found(e):
return render_template('index.html'), 404

关于python - Flask:重定向不存在的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com