Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit values a user can use in a Flask URL parameter

Tags:

python

flask

I have a Flask view that accepts a url parameter old_del, which can only accept 3 values: 'comma', 'pipe', and 'tab'.

@app.route('/jobs/change-file-del/<str:file_location>/<str:old_del>') 
def process_feed(file_location, old_del='tab'):
    ...

I want to return an error if the user includes an invalid value for old_del. I can accomplish this using an assert statement, but is there a way to do this specifically with Flask?

like image 861
Moe Chughtai Avatar asked Jan 29 '23 07:01

Moe Chughtai


1 Answers

There is a built-in any URL converter. Use that to specify the valid values. If it doesn't match, you'll get a 404.

@app.route('/jobs/change/<str:name>/<any(comma, pipe, tab):delim>')
def process_feed(name, delim='tab'):
    pass

If you want to do a more complex check, you can write your own converter instead.

like image 180
davidism Avatar answered Feb 15 '23 20:02

davidism