官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 嘉义市| 手游| 青海省| 抚顺市| 包头市| 永靖县| 合川市| 东台市| 丰台区| 沅陵县| 宣恩县| 石门县| 苍梧县| 任丘市| 商洛市| 贡觉县| 民权县| 泰安市| 维西| 海林市| 平安县| 三河市| 云南省| 龙游县| 盐池县| 广元市| 新田县| 丰顺县| 德保县| 禹城市| 新丰县| 高安市| 辉县市| 应城市| 同仁县| 平湖市| 郯城县| 原平市| 平罗县| 蓝田县| 孝昌县|