加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:47:08 所属栏目:Python 来源:网络整理
导读:我被告知要执行以下操作:修改app.py文件,以便我的网站响应所有可能的URL(也就是不存在的扩展名,如’/ jobs’,这意味着如果输入的URL无效,则会重定向到home索引.html页面.这是我的app.py的副本,有关如何执行此操作的任何想法? from flask import Flask,rend
我被告知要执行以下操作:修改app.py文件,以便我的网站响应所有可能的URL(也就是不存在的扩展名,如’/ jobs’,这意味着如果输入的URL无效,则会重定向到home索引.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.htmls内容可能是:

{% 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读