How to change UserDoesNotExist SELECT behavior in Flask-peewee - python & mysql
Asked Answered
R

1

5

Im using flask-peewee to make an API and I'd like to return back a 404 json if user doesn't exist in the table but seems like it's throwing 500 error instead of 404 error json:

Here is the Error I'm getting:

UserDoesNotExist: instance matching query does not exist:
SQL: SELECT t1.`id`, t1.`username`, t1.`password`, t1.`email`, t1.`token`, t1.`join_date`, t1.`active`, t1.`admin` FROM `user` AS t1 WHERE ((t1.`active` = %s) AND (t1.`username` = %s))
[Wed Sep 18 20:26:24 2013] [error] [client 173.225.41.154] PARAMS: [True, u'fery3']

Code:

@app.route('/api/login/',  methods=['POST'])
def authenticate1():
    if request.method == 'POST' and request.form['username']:
        active = User.select().where(User.active==True)
        user2 = User.select().where(User.username==request.form['username']).get()
        try:
            user = active.where(User.username==request.form['username']).get()
        except exceptions:  # includes simplejson.decoder.JSONDecodeError
            return make_response(jsonify( { 'error': 'Bad request' } ), 400)
        else:
            if not user.check_password(request.form['password']):
                return make_response(jsonify( { 'error': 'Bad request','message': 'Wrong Username or Password'} ), 400)
        return make_response(jsonify( { "meta":{'model':'login','code':'200','status':'ok','message':'successfully loggedin'},'objects':[{'username': user2.username,'email':user2.email,'token' : user2.token }] } ), 200)
Rabi answered 18/9, 2013 at 20:38 Comment(0)
J
10
active = User.select().where(User.active == True)
try:
    user = active.where(User.username == request.form['username']).get()
except User.DoesNotExist:
    return make_response(jsonify({'error': 'Bad request'}), 400)
else:
    if not user.check_password(...)
Jaffa answered 18/9, 2013 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.