上QQ阅读APP看书,第一时间看更新
Performing the action
Finally, we get to the specific part where the input data is clean and ready to use, and we know how to return the result. This part likely involves performing some database query or queries and composing the results. Let's look at the following as an example:
@api_namespace.route('/thoughts/')
class ThoughtList(Resource):
@api_namespace.doc('list_thoughts')
@api_namespace.marshal_with(thought_model, as_list=True)
@api_namespace.expect(search_parser)
def get(self):
'''
Retrieves all the thoughts
'''
args = search_parser.parse_args()
search_param = args['search']
# Action
query = ThoughtModel.query
if search_param:
query =(query.filter(
ThoughtModel.text.contains(search_param)))
query = query.order_by('id')
thoughts = query.all()
# Return the result
return thoughts
You can see here, after parsing the parameters, we use SQLAlchemy to retrieve a query that, if the search parameter is present, will apply a filter. We obtain all the results with all(), returning all the ThoughtModel objects.
Returning the objects marshals (encodes them into JSON) them automatically, as we specified in the marshal_with decorator.