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)?
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()
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)?
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()