Catch all routes for Flask

Question:

I’m using Flask with React. I’d like to create a catch all route similar to something like this (although this doesn’t work):

@app.route('*')
def get():
    return render_template('index.html')

Since my app will use React and it’s using the index.html to mount my React components, I’d like for every route request to point to my index.html page in templates. Is there a way to do this (or is using a redirect the best way)?

Asked By: hidace

||

Answers:

You can follow this guideline: https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations

from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()
Answered By: I. Helmot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.