Skip to content

Commit 8b7b249

Browse files
authored
Add description args for description of abort()
author: Kcrong Origin PR: pallets-eco#636
2 parents 0fc7081 + 367305d commit 8b7b249

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

docs/queries.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,8 @@ This will raise 404 errors instead of returning `None`::
126126
def show_user(username):
127127
user = User.query.filter_by(username=username).first_or_404()
128128
return render_template('show_user.html', user=user)
129+
130+
131+
Also, if you want to add a description with abort(), you can use it as argument as well.
132+
133+
>>> User.query.filter_by(username=username).first_or_404(description='There is no data with {}'.format(username))

flask_sqlalchemy/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -414,20 +414,20 @@ class BaseQuery(orm.Query):
414414
Override the query class for an individual model by subclassing this and setting :attr:`~Model.query_class`.
415415
"""
416416

417-
def get_or_404(self, ident):
417+
def get_or_404(self, ident, description=None):
418418
"""Like :meth:`get` but aborts with 404 if not found instead of returning ``None``."""
419419

420420
rv = self.get(ident)
421421
if rv is None:
422-
abort(404)
422+
abort(404, description=description)
423423
return rv
424424

425-
def first_or_404(self):
425+
def first_or_404(self, description=None):
426426
"""Like :meth:`first` but aborts with 404 if not found instead of returning ``None``."""
427427

428428
rv = self.first()
429429
if rv is None:
430-
abort(404)
430+
abort(404, description=description)
431431
return rv
432432

433433
def paginate(self, page=None, per_page=None, error_out=True, max_per_page=None):

tests/test_query_property.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pytest
2+
from werkzeug.exceptions import NotFound
23

34
import flask_sqlalchemy as fsa
45

@@ -28,3 +29,27 @@ def test_app_bound(db, Todo):
2829
db.session.add(todo)
2930
db.session.commit()
3031
assert len(Todo.query.all()) == 1
32+
33+
34+
def test_get_or_404(Todo):
35+
with pytest.raises(NotFound):
36+
Todo.query.get_or_404(1)
37+
38+
expected = 'Expected message'
39+
40+
with pytest.raises(NotFound) as e_info:
41+
Todo.query.get_or_404(1, description=expected)
42+
43+
assert e_info.value.description == expected
44+
45+
46+
def test_first_or_404(Todo):
47+
with pytest.raises(NotFound):
48+
Todo.query.first_or_404()
49+
50+
expected = 'Expected message'
51+
52+
with pytest.raises(NotFound) as e_info:
53+
Todo.query.first_or_404(description=expected)
54+
55+
assert e_info.value.description == expected

0 commit comments

Comments
 (0)