Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: redirecting nonexistent URL's

Tags:

python

flask

web

I was given instructions to do the following: modify an app.py file so that my website responds to all possible URLs (aka nonexistent extension like '/jobs', meaning that if an invalid URL is entered, it is redirect to the home index.html page. Here is a copy of my app.py as it stands, any ideas on how to do this?

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
like image 236
Iz M Avatar asked Nov 20 '15 03:11

Iz M


1 Answers

I think that what you are looking for is probably just error handling. The Flask documentation has a section that shows how to do error handling.

But to summarize the important points from there:

from flask import render_template

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

You have an app instance, so you can just add this to your code. It's pretty clear that anytime there is a 404 or page does not exist, 404.html will be rendered.

Assuming you are working with jinja templates 404.htmls contents could be:

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

This requires a base template (here layout.html). Say for now you don't want to work with jinja templating, just use this as a 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>

In your case because you want to see the home page (index.html probably):

@app.errorhandler(404)
def page_not_found(e):
    return render_template('index.html'), 404
like image 190
wgwz Avatar answered Nov 14 '22 21:11

wgwz