Creating dynamic flask route

Issue

I’m attempting to create a dynamic flask route. I want to create a parallel page for my route that internal users can see when they add ‘vo/’ before the URL. So essentially there are two different routes /vo/feedbackform and /feedbackform. I know I could just create two routes in the app, but I’m hoping I can optimize.

@app.route('/<x>feedbackform', methods=['GET', 'POST'])
def feedback_portal(x):
    if x == 'vo/':
        return render_template('feedback_vo.html', title='Inquiry Submission')
    elif x == '':
        return render_template('feedback.html', title='Inquiry Submission')

So far, this only works when the URL using the vo/ in the x part of the URL by my elif isn’t working, and I get an error.

Solution

Building off of @ilias-sp’s answer, I was able to use this code:

@app.route('/feedbackform/', methods=['GET', 'POST'], defaults={'x': None})
@app.route('/<x>/feedbackform/', methods=['GET', 'POST'])
def feedback_portal(x):
    if x=='vo':
        return render_template('feedback_vo.html', title='Inquiry Submission')
    elif x==None:
        return render_template('feedback.html', title='Inquiry Submission')

Answered By – Mike Mann

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published