简体   繁体   English

Flask-Mongoengine API分页

[英]Flask-Mongoengine API Pagination

I'm using MongoDB and Flask to make a JSON API for a mobile app. 我正在使用MongoDB和Flask为移动应用程序创建JSON API。

When the app calls /topics/ it will return a list of topics, but how do i paginate the results efficiently? 当应用程序调用/ topics /时,它将返回主题列表,但是我如何有效地分页结果呢? MongoEngine provides a offset and limit, but that grabs the whole result set before limiting and such, which is not very efficient if we have thousands of documents. MongoEngine提供了偏移量和限制,但是在限制等之前就获取了整个结果集,如果我们有成千上万的文档,这并不是很有效。

@app.route('/topics/<int:limit>/<int:page>', methods=['GET'])
def get_topics(limit=25, page=1):
    if limit is None or limit <= 1: 
        limit = 2

    if page is None or page <= 1:
        page = 1

    offset = (page - 1) * limit
    topics = Topic.objects().limit(limit).skip(offset)

Actually, mongoengine does queries with limit and skip parameters in mongodb. 实际上,mongoengine在mongodb中使用limitskip参数进行查询。 You can verify that by using explain to the query and have it return the execution plan instead of the results. 您可以通过对查询使用explain进行验证,并使其返回执行计划而不是结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM