3

How to throw an exception if url query string spelling is wrong?

Explanation :

this is the url to get particular user: http://127.0.0.1:5000/v1/t/user/?user_id=1. if endures will hit http://127.0.0.1:5000/v1/t/user/ it will give list of users.

Question:

what if user_id spelling is wrong in query string ,like by mistake use_id=1, or instead of passing integer value, string value is passing to user_id I hope in this case I should return 404 page. I don't think internally request.args.get() will throw? if I have to handle this scenarios how to do?

Some part of my code:

page_index = request.args.get('index', 1, type=int)
max_item = request.args.get('max', 1, type=int)
userID = request.args.get('user_id', type=int)
VVK kumar
  • 267
  • 3
  • 5
  • 15

1 Answers1

7

You could, create a custom error handler:

@app.errorhandler(404)
def page_not_found(error):
   return render_template('404.html', title = '404'), 404

Then use abort to raise this if the user_id param is not set:

from flask import abort

userID = request.args.get('user_id', type=int)

if not userID:
    abort(404)

Remember, request.args.get returns None as default, unless you give it the default argument:

foo = request.args.get('bar', default='Something')

EDIT: clarification.

If you specify the type argument to request.args.get this will return None if the value passed in the request is not of said type.

So for example:

incoming_data['user_id'] = request.args.get('user_id' , type=int)
print('Got: ', incoming_data['user_id'])

Will result in:

# request: /?user_id=1
Got: 1

# request: /?user_id=test
Got: None

# request: /?
Got: None

As per my other answer, linked in the comment, you can then build the filter accordingly:

filter_data = {key: value for (key, value) in incoming_data.items()
           if value}

result = MyModel.query.filter_by(**filter_data)

filter_data will only contain the key user_id if what was passed in the URL param was an integer.

v25
  • 7,096
  • 2
  • 20
  • 36
  • Agree with your comment but in my case request query string parameter is optional . if it is not there i have to return all the user details . – VVK kumar Dec 11 '19 at 12:18
  • @VVKkumar Possibly see my [recent answer](https://stackoverflow.com/a/59275161/2052575) which deals with potentially not-present variables. – v25 Dec 11 '19 at 13:08
  • I have edited my explanation can you please go through once . The one you have answer its different scenarios , basically i meant how to validate query string ? – VVK kumar Dec 11 '19 at 13:22
  • @VVKkumar See my edit, hopefully this clarifies things. – v25 Dec 11 '19 at 14:23
  • Yes, i got it how to work around it. Thanks a lot man. – VVK kumar Dec 12 '19 at 05:41