Membuat Pagination di Flask + MongoDB

Pertama, kita butuh flask extension yang bernama flask-paginate

https://pythonhosted.org/Flask-paginate/

Kemudian tambahkan baris berikut di route yang mau di-paginasi, misal search result:

from flask_paginate import Pagination, get_page_parameter

@app.route("/search/<keyword>")
def search(keyword):
	page = request.args.get(get_page_parameter(), type=int, default=1)
	per_page = 3
	offset = (page - 1) * per_page
	data = db.product.find({'$text': {'$search': keyword}}, {'score':
		{'$meta':
		'textScore'}}).sort([('score', {'$meta': 'textScore'})]).skip(offset).limit(per_page)

	pagination = Pagination(page=page,
		per_page=per_page,
		total=data.count(),
		css_framework='bootstrap3',
		search=False,
		record_name='products')

	keyword_title = keyword.replace('-', ' ').title()
	return render_template("search.html",
		keyword_title=keyword_title,
		data=data,
		pagination=pagination
	)

Selanjutnya di template search.html:

{% for i in data %}
<p>{{ i['title'] }}</p>
{% endfor %}

{{ pagination.info }}
{{ pagination.links }}

Langkah-langkahnya adalah:

  1. Menentukan per_page (limit di mongo)
  2. Menentukan offset (skip kalau di mongo)
  3. Membuat query ke mongo
  4. Membuat object paginasi
  5. Menampilkan data paginasi
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s