Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Routing with multiple optional parameters

I have a Route named search: @app.route('/search') Is it possible to add multiple optional parameters to it? Example:

@app.route('/search/pg/<int:pg>')
@app.route('/search/types/<types>')
@app.route('/search/number/<int:number>')
@app.route('/search/subject/<subject>')

The order in the URL shouldnt matter, so I could call /search/pg/2, or /search/subject/MySubject/pg/2 or /search/types/posts/subject/MySubject/pg/2

I tried this, but it only works with the full paths and all the parameters:

@app.route('/search/pg/<int:pg>/types/<types>/subject/<subject>', methods=['GET', 'POST'])
@app.route('/search/subject', defaults={'subject', None})
@app.route('/search/pg/<int:pg>/types/<types>', methods=['GET', 'POST'])
@app.route('/search/types', defaults={'types', None})
@app.route('/search', defaults={'pg': 1}, methods=['GET', 'POST'])
@app.route('/search/pg/<int:pg>', methods=['GET', 'POST'])
def search(pg, types=None, subject=None):
    pass
like image 667
David Carneiro Avatar asked Oct 23 '25 09:10

David Carneiro


1 Answers

You can use filter in the URL instead of "sub-resources". Then you can put search arguments in any order in your request: /search?pg=<pg>&types=<types>

Inside the flask view function you can retrieve parameters from the request object:

@app.route('/search/')
def search():
    pg = request.args.get('pg')
    ...
like image 158
lee-pai-long Avatar answered Oct 25 '25 22:10

lee-pai-long



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!