pythonflaskcouchbasecouchbase-view

How to make the endpoint faster to load?


I am new to couchbase and perhaps toward frontend programming. I am having a peice of code which creates object of couchbase db and then fetches the view from the db. The problem is that it fetches all the data from begining of time that database has. My focus is to make this faster such that this gets displayed faster on site. Here is the piece of code

@app.route("/all-schools", methods=['GET'])
def past_school_schedules():

    return render_template('schb.get_view('cloud', 'christmast-past'))

So once couchbase fetches all the views and displays it it takes like 30-40 sec .. which is huge since it renders the temp


Solution

  • Use pagination to render the data in small batches, decide page size as per your requirement such that you have sufficient data to processed/displayed on UI on the first call and make the subsequent call to fetch even more data on request using next_page_url.

    Flask-SQLAlchemy supports pagination natively with the paginate() query method

    The paginate method can be called on any query object from Flask-SQLAlchemy. It takes three arguments:

    1. the page number, starting from 1
    2. the number of items per page
    3. an error flag. If True, when an out of range page is requested a 404 error will be automatically returned to the client. If False, an empty list will be returned for out of range pages.

    The return value from paginate is a Pagination object. The items attribute of this object contains the list of items in the requested page.

    Below is the updated code using pagination.

    @app.route("/all-schools-schedule/christmas-past", methods=['GET'])
    def past_school_schedules():
        # this creates couchbase object
        cb = get_db().paginate(
            page, POSTS_PER_PAGE, False)
            return render_template('school_schedule.html', past=cb.items)
    

    Hope this helps!