Home > Blockchain >  Flask Route: pattern matching to exclude certain routes
Flask Route: pattern matching to exclude certain routes

Time:01-05

I have the following routes already set up:


@app.route("/")
@app.route("/index")
def index():
    ...


@app.route("/projects/<projname>")
def projects(projname):
    ...

@app.route("/extras/")
def extras():
    ...

@app.route("/extras/<topic>/")
def extras_topics(topic):
    ...


To this, I would like to add a view into a route that matches any pattern excluding the existing routes, something like:


@app.route("/<pagename>")   # this excludes /index, /projects, and /extras
def page_view(pagename):
    ...

So if one wanted to get to /research, it should trigger page_view(), but for / or /index I'd like to trigger index()

What would be ways to go about this?

CodePudding user response:

If I am correctly understanding your question you are essentially asking to create a route for any URL that is not already defined. These routes would usually raise a 404 error (Page not found), so you can use Flask's built-in error-handlers to catch any page you haven't defined.

This code should do that, and I have also included a way to get the path that raised the 404:

from flask import request
app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    pagename = request.path # Returns the URL that raised the 404.

I hope this solves your issue!

  • Related