2015-11-20 99 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」? –