如何更改 Flask-peewee 中的 UserDoesNotExist SELECT 行为 - python & mysql
Posted
技术标签:
【中文标题】如何更改 Flask-peewee 中的 UserDoesNotExist SELECT 行为 - python & mysql【英文标题】:How to change UserDoesNotExist SELECT behavior in Flask-peewee - python & mysql 【发布时间】:2013-09-23 18:50:30 【问题描述】:我正在使用flask-peewee 制作 API,如果用户在表中不存在,我想返回 404 json,但似乎抛出 500 错误而不是 404 错误 json:
这是我得到的错误:
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']
代码:
@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)
【问题讨论】:
【参考方案1】: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(...)
【讨论】:
以上是关于如何更改 Flask-peewee 中的 UserDoesNotExist SELECT 行为 - python & mysql的主要内容,如果未能解决你的问题,请参考以下文章