Bootstrap FreeKB - Flask - Catch All Route
Flask - Catch All Route

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

In Flask, HTTP headers are made available using request. Let's say your flask project has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

Let's say you want to redirect users to a sort of default catch all page if an endpoint is used for which a route doesn't exist. In this super simple example, any endpoint other than / will go to the catch all route.

from flask import Flask

app = Flask(__name__)

@app.route('/', defaults={'my_path': ''})
@app.route('/<path:my_path>')
def catch_all(my_path):
  return "Your endpoint is /"+my_path

 

So, for example, if /foo/bar is used, the catch_all route will be used and the following should be returned.

Your endpoint is /foo/bar

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a2c417 in the box below so that we can be sure you are a human.