44

In Cherrypy it's possible to do this:

@cherrypy.expose
def default(self, url, *suburl, **kwarg):
    pass

Is there a flask equivalent?

John Jiang
  • 11,069
  • 12
  • 51
  • 60

4 Answers4

65

There is a snippet on Flask's website about a 'catch-all' route for flask. You can find it here.

Basically the decorator works by chaining two URL filters. The example on the page is:

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path

Which would give you:

% curl 127.0.0.1:5000          # Matches the first rule
You want path:  
% curl 127.0.0.1:5000/foo/bar  # Matches the second rule
You want path: foo/bar
Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
alemangui
  • 3,571
  • 22
  • 33
7
@app.errorhandler(404)
def handle_404(e):
    # handle all other routes here
    return 'Not Found, but we HANDLED IT
David
  • 71
  • 1
  • 1
1

If you single page application has nested routes (e.g. www.myapp.com/tabs/tab1 - typical in Ionic/Angular routing), you can extend the same logic like this:

@app.route('/', defaults={'path1': '', 'path2': ''})
@app.route('/<path:path1>', defaults={'path2': ''})
@app.route('/<path:path1>/<path:path2>')
def catch_all(path1, path2):
    return app.send_static_file('index.html')
Darien Pardinas
  • 5,910
  • 1
  • 41
  • 48
0

The below works for all requests, including PUT, PATCH and other unheard methods, wheres other answer don't

from flask import Flask
from werkzeug.routing import Rule

app = Flask(__name__)


@app.endpoint("catch_all")
def _404(_404):
    return "", 404


app.url_map.add(Rule("/", defaults={"_404": ""}, endpoint="catch_all"))
app.url_map.add(Rule("/<path:_404>", endpoint="catch_all"))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=True)