'Flask routing multiple optional parameters using url_for()
I know there are similar questions on this but they don't seem to fit my case outlined below:
I use one optional parameter in many of my routes like this.
@bp.route('/page1', methods=["GET", "POST"])
@bp.route('/page1/<foo>', methods=["GET", "POST"])
def page1(foo=None):
if foo:
# do foo stuff
This is called with url_for('page1') or url_for('page1', foo=3) and it works just fine.
I would like to optionally use additional parameters like this:
url_for('page2', foo=4) or url_for('page2', bar= 5) or url_for('page2', foo=4, bar=5)
I tried this.
@bp.route('/page2', methods=["GET", "POST"])
@bp.route('/page2/<foo>/<bar>', methods=["GET", "POST"])
def page1(foo=None, bar=None):
if foo:
# do foo stuff
if bar:
#do bar stuff
I was hoping that url_for() would be smart enough to build the request in the correct order if a parameter was missing since they are known and named - but it does not. Perhaps empty slot like page2//5 is just not allowed.
Further, url_for('page2', foo=None, bar= 5) seems to be illegal ( pycharm will not run it) and url_for('page2', foo='', bar= 5) will cause a runtime error.
The only thing that does work is url_for('page2', foo='ignorestring', bar= 5)
So, I can make this work but have to populate my unused variable(s) with something (instead of None or empty string) which makes for ugly code!
Any ideas how to do this cleanly without resorting to less secure querystrings?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|