Reputation: 1
I am trying to implement dynamic routing with flask. It works except for when the route is '/'. Here is my code:
from flask import Flask, render_template,
app = Flask(__name__)
@app.route('/favicon.ico')
def favicon():
'''create favicon'''
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/<string:page_name>')
def html_page(page_name):
'''' dynamic routing of template pages'''
return render_template(page_name)
it returns this error: 127.0.0.1 - - [05/Oct/2022 20:45:53] "GET / HTTP/1.1" 404 -
Upvotes: 0
Views: 280
Reputation: 126
The problem is that the @app.route('/<string:page_name>')
assumes that page_name
is not an empty string (as it would be for requesting /).
The fix is simple, simply add an extra @app.route and set a default value for page_name:
from flask import Flask, render_template,
app = Flask(__name__)
@app.route('/favicon.ico')
def favicon():
'''create favicon'''
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/', defaults={'page_name': 'index.html'}) # Adds route for /, with page_name='index.html'
@app.route('/<string:page_name>')
def html_page(page_name):
'''dynamic routing of template pages'''
return render_template(page_name)
You may want to adjust the default value of page_name to be something that makes sense for your application. I am assuming here that you have a template called index.html
.
Upvotes: 2