Issue
While making a web app in Flask, I'm finding I have a big list of views that look exactly like these:
@app.route('/home', methods=['GET'])
@require_login
def home():
return render_template("home.html")
@app.route('/files', methods=['GET'])
@require_login
def files():
return render_template("files.html")
Is there some way I could make a list like ['home','files'] and generate all of those simple views from it?
Solution
If routes
and templates
names match, you can do the following:
@app.route('/home', methods=['GET'])
@app.route('/files', methods=['GET'])
@require_login
def just_render():
file_name = request.path.replace('/', '')
template = '{file_name}.html'.format(file_name=file_name)
return render_template(template)
i.e. get the requested path from request.path
, remove unwanted /
and then format the template name.
EDIT
To answer your question from the comments:
Is there any way I could compress the list of routes?
I would amend a bit @Sean Vieira's answer from the comments:
@app.route('/<path>', methods=['GET'])
@require_login
def just_render(path):
if path in ['home', 'files', 'about', 'contact']:
template = '{file_name}.html'.format(file_name=path)
return render_template(template)
Answered By - Dušan Maďar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.