def index(): perpage = current_app.config['GALLERY_PERPAGE'] page = request.args.get('page', 1, type=int) key = request.args.get('key', '') base_query = Image.query if current_user.is_anonymous(): base_query = base_query.filter(Image.public==1) query = base_query if key: ikey = '%' + key + '%' query = query.filter(db.or_(Image.source_name.ilike(ikey), Image.title.ilike(ikey), Image.tag.ilike(ikey))) query = query.order_by(Image.create_at.desc()) page_obj = query.paginate(page=page, per_page=perpage) page_url = lambda page : url_for('gallery.index', page=page) recents = base_query.order_by(Image.create_at.desc()).offset(0).limit(perpage) kwargs = { 'key' : key, 'page_obj': page_obj, 'page_url': page_url, 'recents' : recents } return render_template('gallery/index.html', **kwargs)