Skip to content

Instantly share code, notes, and snippets.

@matsub
Created December 14, 2016 14:36
Show Gist options
  • Save matsub/efe3a79e0992de937b72822983736324 to your computer and use it in GitHub Desktop.
Save matsub/efe3a79e0992de937b72822983736324 to your computer and use it in GitHub Desktop.
An example to paginate with bottlepy.

about this

This is an example to paginate with bottlepy. To run this,

  1. install bottle and bottle_sqlite
  2. run python db_init.py
  3. run python bottle_pagination.py

behavior

This runs at localhost:8080/users/. This program shows users in a database table using pagination. The number of users per page can be specified with the query string per. (default is 10.)

e.g.

The points of this example

  • Request Routing
    With dynamic routing, you can paginate from the URL string. Watch below document about Request Routing. http://bottlepy.org/docs/dev/routing.html
  • Fetching records from specific range
    Fetch records from specific range using the page number which got from dynamic routes, and pass them to the template.
  • Head and Tail of pagination
    In the first and last page, links to paginate should be excluded. To do this, you can use the template's control syntax.
import sqlite3
import bottle
from bottle import (
jinja2_template as template,
request,
)
from bottle_sqlite import SQLitePlugin
app = bottle.Bottle()
PER_PAGE = 10
db = sqlite3.connect('example.db')
USER_TOTAL, = db.execute('SELECT COUNT(*) FROM users').fetchone()
@app.route('/users/')
@app.route('/users/<page:int>')
def pagination(db, page=0):
# number of records per page
per = int(request.query.per or PER_PAGE)
start, end = page*per, (page+1)*per
# fetch records
users = db.execute('SELECT * FROM users WHERE id >= ? AND id < ?', (start, end))
keys = ('id', 'name')
users = (dict(zip(keys, user)) for user in users)
parameters = {
'page': page,
'users': users,
'has_next': end < USER_TOTAL,
'query_string': '?'+request.query_string,
}
return template("pagination.html", **parameters)
if __name__ == '__main__':
app.install(SQLitePlugin(dbfile='example.db'))
app.run(port=8080, reloader=True)
import string
import random
import sqlite3
name = lambda n: ''.join(random.choice(string.ascii_letters) for _ in range(n))
with sqlite3.connect('example.db') as db:
# initialize table
db.execute('drop table if exists users')
db.execute('create table users (id, name)')
# initialize users
users = ((i, name(6)) for i in range(100))
db.executemany('insert into users values (?,?)', users)
db.commit()
<ul>
{% for user in users %}
<li>{{ user.id }}: {{ user.name }}</li>
{% endfor %}
</ul>
<nav>
{% if page > 0%}
{% if page == 1 %}
<a href="./{{ query_string }}">prev</a>
{% else %}
<a href="{{ page-1 }}{{ query_string }}">prev</a>
{% endif %}
{% endif %}
{% if has_next %}
<a href="{{ page+1 }}{{ query_string }}">next</a>
{% endif %}
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment