2015-11-20 100 views
1

我被指示执行以下操作:修改app.py文件,以便我的网站响应所有可能的URL(也就是不存在的扩展名,如'/ jobs',这意味着如果输入了无效的URL ,它被重定向到家里index.html页面。这里是我的app.py的副本,因为它代表,就如何做到这一点任何想法?烧瓶:重定向不存在的URL

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 
+1

http://flask.pocoo.org/snippets/57/ – MaxNoe

+0

参见,[如何捕获在路径的任意路径(http://stackoverflow.com/questions/15117416/捕获任意路径在烧瓶路由/),虽然404处理程序在这种情况下更有意义。 – davidism

回答

5

我认为你正在寻找的东西可能是只是错误处理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将被呈现。

假设你与神社模板工作404.html S的含量可能是:

{% 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)。假设现在你不想与神社模板去上班,就以此为404.html:因为你想看到主页(的index.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> 

你的情况):

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

嗨,谢谢你的回答。为什么该函数定义说>>>无效的参数名称“e”? –