John Jiang
John Jiang

Reputation: 11509

Python - Flask Default Route possible?

In Cherrypy it's possible to do this:

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

Is there a flask equivalent?

Upvotes: 44

Views: 38881

Answers (4)

David
David

Reputation: 91

@app.errorhandler(404)
def handle_404(e):
    # handle all other routes here
    return 'Not Found, but we HANDLED IT'

Upvotes: 9

user18511546
user18511546

Reputation:

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)

Upvotes: 1

alemangui
alemangui

Reputation: 3655

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

Upvotes: 68

Darien Pardinas
Darien Pardinas

Reputation: 6196

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')

Upvotes: 1

Related Questions