Exemplo n.º 1
0
def myservices():
    from shops import ContractedProduct, Product, Shop
    from invoices import Order, Orderlist
    from pagination import Pagination
    from adminsettings import Adminsettings
    Adminsettings(db)
    ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    records = db((db.contractedproducts.id > 0)
                 & (db.contractedproducts.user == auth.user_id)).count()
    items_per_page = settings.orderlistitems
    pag = Pagination(records, items_per_page)
    contractedproducts = db((db.contractedproducts.id > 0) & (
        db.contractedproducts.user == auth.user_id)).select(
            db.contractedproducts.ALL,
            db.products.ALL,
            db.shop.ALL,
            db.auth_user.ALL,
            db.fiscals.ALL,
            left=[
                db.products.on(
                    db.products.id == db.contractedproducts.product),
                db.shop.on(db.shop.id == db.contractedproducts.shop),
                db.auth_user.on(db.auth_user.id == db.contractedproducts.user),
                db.fiscals.on(db.fiscals.user == db.auth_user.id)
            ],
            orderby=~db.contractedproducts.expiration,
            limitby=pag.limitby())

    return dict(contractedproducts=contractedproducts,
                pagination=pag,
                records=records,
                items_per_page=items_per_page)
Exemplo n.º 2
0
def contractedproducts():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):

		from shops import ContractedProduct, Product, Shop
		from invoices import Order, Orderlist
		from pagination import Pagination
		ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		records=db(db.contractedproducts.id>0).count()
		items_per_page=settings.orderlistitems
		pag=Pagination(records, items_per_page)
		contractedproducts = db(db.contractedproducts.id>0).select(	db.contractedproducts.ALL,
														db.products.ALL,
														db.shop.ALL,
														db.auth_user.ALL,
														db.fiscals.ALL,
														left=[	db.products.on(db.products.id==db.contractedproducts.product),
																db.shop.on(db.shop.id==db.contractedproducts.shop),
																db.auth_user.on(db.auth_user.id==db.contractedproducts.user),
																db.fiscals.on(db.fiscals.user==db.auth_user.id)],
														orderby=~db.contractedproducts.expiration, limitby=pag.limitby())

		return dict(contractedproducts=contractedproducts, pagination=pag, records=records, items_per_page=items_per_page)

	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 3
0
def orders():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from shops import Shop, ContractedProduct
		from invoices import Order, Orderlist
		from pagination import Pagination
		Order(db), Orderlist(db), Shop(db), ContractedProduct(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		records=db(db.orders.status!="CreandoAdmin").count()
		items_per_page=settings.orderlistitems
		pag=Pagination(records, items_per_page)
		#orders = db(db.orders.status!="CreandoAdmin").select(db.orders.ALL, orderby=~db.orders.id, limitby=pag.limitby())

		orders=db(db.orders.status!="CreandoAdmin").select(db.orders.ALL, 
													
													db.shop.host,
													left=[	db.orderlist.on(db.orderlist.g_order==db.orders.id),
															db.contractedproducts.on(db.contractedproducts.orderlist==db.orderlist.id),
															db.shop.on(db.shop.id==db.contractedproducts.shop)],
													orderby=~db.orders.id,
													groupby=db.orders.id, 
													limitby=pag.limitby())




		return dict(orders=orders, pagination=pag, records=records, items_per_page=items_per_page)

	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 4
0
 def test_get_pagination_links(self):
     p = Pagination(total=100, per_page=10, current=5)
     expect = [
         {
             "page": 3,
             "is_current": False
         },
         {
             "page": 4,
             "is_current": False
         },
         {
             "page": 5,
             "is_current": True
         },
         {
             "page": 6,
             "is_current": False
         },
         {
             "page": 7,
             "is_current": False
         },
     ]
     self.assertEqual(expect, p.get_pagination_links(num=5))
Exemplo n.º 5
0
def index():
    db = get_db()
    try:
        page = int(request.args.get('p', 1))
    except ValueError:
        page = 1
    search_query = request.args.get('q')
    if search_query:
        egg = "%{}%".format(search_query[:20])
        articles = db.execute(
            "select slug, title, intro, date from articles "
            "where published and (title like ? or intro like ?) "
            "order by date desc limit ?", [egg, egg, PER_PAGE])
        pagination = Pagination(1, PER_PAGE, PER_PAGE)
    else:
        cnt = db.execute(
            "select count(*) from articles where published").fetchone()[0]
        pagination = Pagination(page, PER_PAGE, cnt)
        articles = db.execute(
            "select slug, title, intro, date from articles where published "
            "order by date desc "
            "limit ? offset ?", [PER_PAGE, (pagination.page - 1) * PER_PAGE])
    return render_template('index.html',
                           articles=articles,
                           pagination=pagination)
Exemplo n.º 6
0
 def __init__(self, connection_details, api_name="jira"):
     logger.info("JiraClient init")
     self.api_name = api_name
     self.api_url = normalize_url(connection_details.get("api_url", ""))
     self.server_type = connection_details.get("server_type", "cloud")
     self.username = connection_details.get("username", "")
     self.password = connection_details.get("token", "")
     self.subdomain = connection_details.get("subdomain")
     self.ignore_ssl_check = connection_details.get("ignore_ssl_check",
                                                    False)
     self.site_url = self.get_site_url()
     self.params = {}
     self.pagination = Pagination()
Exemplo n.º 7
0
def emailbox():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		from pagination import Pagination
		from mailboxing import Mailboxing
		Mailboxing(db)
		records=db(db.mailbox.id>0).count()
		notreads=db(db.mailbox.messread==False).count()
		items_per_page=settings.messageitems
		pag=Pagination(records, items_per_page)
		messages = db().select(db.mailbox.ALL, orderby=~db.mailbox.id, limitby=pag.limitby())
		return dict(messages=messages, pagination=pag, records=records, items_per_page=items_per_page, notreads=notreads)
	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 8
0
def products():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from shops import Product, PricePlan
		from pagination import Pagination
		Product(db), PricePlan(db)

		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		records=db(db.products.id>0).count()
		items_per_page=settings.productitems
		pag=Pagination(records, items_per_page)
		products=db(db.products.id>0).select(db.products.ALL, db.priceplans.planname, left=[db.priceplans.on(db.priceplans.id==db.products.plan)], orderby=db.products.id, limitby=pag.limitby())
		return dict(products=products, pagination=pag, records=records, items_per_page=items_per_page)
	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 9
0
    def test_init(self):
        pagination = Pagination(total=100, per_page=10, current=1)
        self.assertIsNotNone(pagination)

        with self.assertRaises(ValueError):
            pagination = Pagination(total=-1, per_page=100, current=1)

        with self.assertRaises(ValueError):
            pagination = Pagination(total=100, per_page=-1, current=1)

        with self.assertRaises(ValueError):
            pagination = Pagination(total=100, per_page=10, current=-1)

        with self.assertRaises(ValueError):
            pagination = Pagination(total=100, per_page=10, current=11)
Exemplo n.º 10
0
def blog(page):
    settings = util.get_current_settings()

    posts_with_tags = []
    if current_user.is_authenticated:
        if current_user.admin:
            posts = Post.select().order_by(Post.created_at.desc())
    else:
        posts = Post.select().where(Post.published).order_by(
            Post.created_at.desc())

    number_of_posts = Post.select().count()
    posts = posts.paginate(page, settings.posts_per_page)

    for post in posts:
        tags = Tag.select().join(PostTag).where(PostTag.post == post).order_by(
            Tag.name)
        posts_with_tags.append([post, tags])

    pages = Pagination(page, settings.posts_per_page, number_of_posts, 7)

    if not number_of_posts == 0:
        return render_template('blog_list.html',
                               posts_with_tags=posts_with_tags,
                               pages=pages)
    else:
        notice = "No posts yet  :/"
        return render_template('notice.html', notice=notice)
    def do(self, search, page):
        """Search a term in the Whoosh index."""
        aborted_search = False
        results = []
        num_results = 0
        total_time = 0
        PER_PAGE = 100

        start_time = time.time()

        if search.has_invalid_search_term:
            aborted_search = True
            pagination = None
            glossary = None
        else:
            g = Glossary(search.source)
            g.search()
            glossary = g.get_results()

            raw_results = search.get_results()
            num_results = raw_results.scored_length()

            if len(raw_results) > 0:

                url = request.url
                o = urllib.parse.urlparse(url)
                url = '?' + o.query

                pagination = Pagination(PER_PAGE, len(raw_results), url, page)
                start = (pagination.page - 1) * PER_PAGE
                end = start

                max_end = start + PER_PAGE
                if num_results - start < max_end:
                    end += num_results - start
                else:
                    end += PER_PAGE

                for i in range(start, end):
                    results.append(self.get_result(raw_results[i]))

                pages = pagination.pages
            else:
                pagination = None
                pages = 0

        total_time = time.time() - start_time
        ctx = {
            'source': search.source,
            'target': search.target,
            'project': search.project,
            'num_results': num_results,
            'time': "{:.2f}".format(total_time),
            'aborted_search': aborted_search,
            'glossary': glossary,
            'pages': pages,
            'results': results,
        }

        return ctx
Exemplo n.º 12
0
def user_view(user_name, page):
    settings = util.get_current_settings()

    if current_user.is_authenticated:
        if current_user.admin:
            matches = Post.select().join(PostUser).join(User)\
                .where(User.name == user_name).order_by(Post.created_at.desc())
    else:
        matches = Post.select().where(Post.published).join(PostUser).join(User)\
            .where(User.name == user_name).order_by(Post.created_at.desc())

    number_of_matches = matches.count()
    matches = matches.paginate(page, settings.posts_per_page)

    matches_with_tags = []
    for match in matches:
        tags = Tag.select().join(PostTag)\
            .where(PostTag.post == match).order_by(Tag.name)
        matches_with_tags.append([match, tags])

    pages = Pagination(page, settings.posts_per_page, number_of_matches, 7)

    if not number_of_matches == 0:
        return render_template('user_view.html',
                               posts_with_tags=matches_with_tags,
                               pages=pages,
                               user_name=user_name)
    else:
        notice = "No posts by user " + '"' + str(user_name) + '"!'
        return render_template('notice.html', notice=notice)
Exemplo n.º 13
0
def category_page(cat_id):
    lang = app.config.get("LANGUAGE")
    story_col = story_collect()
    category_col = category_collect()
    page = request.args.get("page", type=int, default=1)

    data_dict = {"language": lang, "category.url": cat_id}
    total_story = story_col.find(data_dict).count(True)
    pagination = Pagination(total_count=total_story, page=page, per_page=PER_PAGE)

    # No story found
    if not (1 <= page <= pagination.total_page):
        abort(404)

    story_list = story_col.find(data_dict)\
        .sort("story_id", -1)\
        .skip(PER_PAGE*(page-1))\
        .limit(PER_PAGE)

    category_list = category_col.find()
    category_obj = category_col.find_one({"url": cat_id})
    ref_url = "{0}{1}/{2}/".format(request.host_url, "category", cat_id)

    return render_template('category_page.html',
                           records=story_list,
                           pagination=pagination,
                           category_list=category_list,
                           ref_url=ref_url,
                           category_obj=category_obj)
Exemplo n.º 14
0
 def paginate(self,
              query: str = "*",
              page: int = 1,
              num: int = 10,
              sort_by: str = 'id',
              direction: bool = True,
              slop: int = 0) -> Pagination:
     try:
         tic = time.perf_counter()
         start = (page - 1) * num
         # count total of docs to calculate the total of pages
         total = self.idx.search(Query(query).slop(slop).paging(0, 0)).total
         # construct the query, paginated start and num
         q = Query(query).slop(slop).sort_by(sort_by,
                                             direction).paging(start, num)
         # perform the query
         items = self.idx.search(q).docs
         elapsed_time = time.perf_counter() - tic
         logger.debug(
             f"Pagination over {self.prefix}({query}) with {num} of {total} results done in {(elapsed_time*1000):0.3f}ms"
         )
         p = Pagination(page=page, per_page=num, total=total, items=items)
         return p
     except Exception as ex:
         raise rSearchException(str(ex), {'query': query})
Exemplo n.º 15
0
def seller_feed(page, product=None):

    if product == None:
        stocks = Stock.select().where(Stock.bought == False).paginate(
            int(page), 100)
        count = Stock.select().where(Stock.bought == False).count()
    else:
        stocks = Product.get(Product.name == product).in_stock.where(
            Stock.bought == False).paginate(int(page), 100)
        count = Product.get(Product.name == product).in_stock.where(
            Stock.bought == False).count()

    stocks = [{
        'id': json.dumps(str(stock.id)),
        'stock': stock,
        'form': forms.OrderForm()
    } for stock in stocks
              ]  # this will be used for adding listings to the homepage

    stock_ids = [stock['id'] for stock in stocks]

    pagination = Pagination(page, 100, count)

    return render_template('admin-feed.html',
                           stocks=stocks,
                           current_user=current_user,
                           Order=Order,
                           Stock=Stock,
                           fn=fn,
                           int=int,
                           pagination=pagination,
                           page=page,
                           os=os,
                           list=list,
                           HOST=HOST)
Exemplo n.º 16
0
    def do(self, search):
        """Search a term in the Whoosh index."""
        results = []
        num_results = 0
        total_time = 0
        PER_PAGE = 100

        start_time = time.time()
        raw_results = search.get_results()
        total_time = time.time() - start_time
        num_results = raw_results.scored_length()

        if len(raw_results) > 0:

            url = request.url.encode('utf-8')
            o = urlparse(url)
            url = self.lletra + '?' + o.query

            pagination = Pagination(PER_PAGE, len(raw_results), url)
            pagination.separator = '?'
            start = (pagination.page - 1) * PER_PAGE
            end = start

            max_end = start + PER_PAGE
            if num_results - start < max_end:
                end += num_results - start
            else:
                end += PER_PAGE

            for i in xrange(start, end):
                results.append(self.get_result(raw_results[i]))

        else:
            pagination = None

        ctx = {
            'results': results,
            'num_results': num_results,
            'time': "{:.2f}".format(total_time),
            'lletra': self.lletra,
            'pagination': pagination,
        }

        env = Environment(loader=FileSystemLoader('./'))
        template = env.get_template('templates/index_letter.html')
        r = template.render(ctx).encode('utf-8')
        return r
Exemplo n.º 17
0
    def do(self, search):
        """Search a term in the Whoosh index."""
        aborted_search = False
        results = []
        num_results = 0
        total_time = 0
        PER_PAGE = 100

        g = Glossary(search.source)
        g.search()
        glossary = g.get_results()

        if search.has_invalid_search_term:
            aborted_search = True
            pagination = None
        else:
            start_time = time.time()
            raw_results = search.get_results()
            total_time = time.time() - start_time
            num_results = raw_results.scored_length()

            if len(raw_results) > 0:

                url = request.url
                o = urllib.parse.urlparse(url)
                url = '?' + o.query

                pagination = Pagination(PER_PAGE, len(raw_results), url)
                start = (pagination.page - 1) * PER_PAGE
                end = start

                max_end = start + PER_PAGE
                if num_results - start < max_end:
                    end += num_results - start
                else:
                    end += PER_PAGE

                for i in range(start, end):
                    results.append(self.get_result(raw_results[i]))
            else:
                pagination = None

        ctx = {
            'source': search.source,
            'target': search.target,
            'project': search.project,
            'results': results,
            'num_results': num_results,
            'time': "{:.2f}".format(total_time),
            'aborted_search': aborted_search,
            'glossary': glossary,
            'pagination': pagination,
        }

        env = Environment(loader=FileSystemLoader('./'))
        template = env.get_template('templates/search_results.html')

        r = template.render(ctx).encode('utf-8')
        return r
Exemplo n.º 18
0
Arquivo: views.py Projeto: qgreg/puppy
def shelterList(page=1):
	count = session.query(Shelter).count()
	offset = (page - 1) * SHELTER_POST_PER_PAGE
	shelter = session.query(Shelter).order_by(Shelter.id).slice(offset, offset + SHELTER_POST_PER_PAGE)
	paginate = Pagination(page, SHELTER_POST_PER_PAGE, count)
	print "Count ", count, "Offset ", offset, "Page ", page, \
		"Limit ", SHELTER_POST_PER_PAGE, "Pages ", paginate.pages
	return render_template('shelterlist.html', shelter = shelter, page = page, paginate = paginate)
Exemplo n.º 19
0
def index(page):
    # Return all articles and display them in the index template
    num_posts = model.count_articles()
    pagination = Pagination(page, num_posts)
    articles = model.get_articles(page)
    return render_template('index.html',
                           articles=articles,
                           pagination=pagination)
Exemplo n.º 20
0
def subscriptions():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from pagination import Pagination
		from regnews import Regnews
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		try:
			reg=Regnews(db)
			reg.define_tables()
		except:
			pass
		records=db(db.regnews.id>0).count()
		items_per_page=settings.subscriptionitems
		pag=Pagination(records, items_per_page)
		subscriptions = db().select(db.regnews.ALL, orderby=~db.regnews.id, limitby=pag.limitby())
		return dict(subscriptions=subscriptions, pagination=pag, records=records, items_per_page=items_per_page, actives=db(db.regnews.news==True).count())
	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 21
0
def show_industry_results(page):
    form = forms.IndustrycodeSearchForm(request.form)
    search_string = form.search.data
    checkbox = form.checkbox.data
    search_from = form.searchfrom.data
    search_to = form.searchto.data

    if page == 1:
        if not form.validate_on_submit():
            #  pass the checkbox so we can show the correct from/to pane
            return render_template('industrycode.html',
                                   form=form,
                                   tabs=tabs,
                                   visible=checkbox)

    if page == 1:
        session['search_string'] = search_string
        filters = json.loads(form.search_industry_filters.data)
        session['filters'] = filters
        session['checkbox'] = checkbox
        session['search_from'] = search_from
        session['search_to'] = search_to
    else:
        search_string = session['search_string']
        filters = session['filters']
        checkbox = session['checkbox']
        search_from = session['search_from']
        search_to = session['search_to']

    try:
        results = search.search_industry(search_string, search_from, search_to,
                                         filters, page)
    except Exception as inst:
        try:
            reason = inst.info['error']['root_cause'][0]['reason']
        except (NameError, TypeError, AttributeError):
            reason = inst

        a = list(form.search.errors)
        a.append(reason)
        form.search.errors = tuple(a)
        form.search.data = None
        return render_template('industrycode.html',
                               form=form,
                               tabs=tabs,
                               visible=checkbox)

    count = results['total']

    if not results and page != 1:
        abort(404)

    pagination = Pagination(page, Config.ITEMS_PER_PAGE, count)
    return render_template('results.html',
                           pagination=pagination,
                           companies=results,
                           tabs=tabs,
                           view=view_type)
Exemplo n.º 22
0
def parkinfo(request):
    # 获取parkinfo数据表中的所有记录
    park_lists = Parkinfo.objects.order_by('park_id')

    current_page = request.GET.get('p')

    count = Parkinfo.objects.all().count()

    page_obj = Pagination(current_page,
                          count,
                          page_url="parkmanage/parkinfo.html")

    data_list = park_lists[page_obj.start_page_item():page_obj.end_page_item()]

    return render_to_response('parkmanage/parkinfo.html', {
        'parklists': data_list,
        'page_obj': page_obj
    })
Exemplo n.º 23
0
def bloglist():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from pagination import Pagination
		from blog import Blog, Draft, Images
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		blog=Blog(db,ckeditor)
		draft=Draft(db,ckeditor)
		Images(db)
		brecords=db(db.blog.id>0).count()
		drecords=db(db.draft.id>0).count()
		records = int(brecords) + int(drecords)
		items_per_page=settings.bloglistitems
		pag=Pagination(records, items_per_page)
		drafts =db().select(db.draft.ALL, orderby=~db.draft.id, limitby=pag.limitby())
		posts = db().select(db.blog.ALL, orderby=~db.blog.id, limitby=pag.limitby())
		return dict(posts=posts, drafts=drafts, pagination=pag, records=records, items_per_page=items_per_page)
	else:
		redirect(URL(request.application,'blog','index'))
Exemplo n.º 24
0
Arquivo: views.py Projeto: qgreg/puppy
def puppyList(page=1):
	count = session.query(Puppy).count()
	offset = (page - 1) * PUPPY_POST_PER_PAGE
	puppy = session.query(Puppy).order_by(Puppy.id).slice(offset, offset + PUPPY_POST_PER_PAGE)
	paginate = Pagination(page, PUPPY_POST_PER_PAGE, count)
	profile = session.query(PuppyProfile).all()
	print "Count ", count, "Offset ", offset, "Page ", page, \
		"Limit ", PUPPY_POST_PER_PAGE, "Pages ", paginate.pages
	return render_template('puppylist.html', puppy = puppy, profile = profile, page = page, paginate = paginate)
Exemplo n.º 25
0
def index(): 
	from pagination import Pagination
	from blog import Blog, Images
	from comments import Comments
	from adminsettings import Adminsettings, Cifrar
	Adminsettings(db)
	Blog(db,ckeditor), Images(db)
	Comments(db)
	settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
	session.publishing=False
	session.preview=False
	records=db(db.blog.id>0).count()
	items_per_page=settings.blogitems
	pag=Pagination(records, items_per_page)
	posts = db(db.blog.public==True).select(db.blog.ALL, orderby=~db.blog.id, limitby=pag.limitby(), cache=(cache.ram, 5), cacheable=True)
	lastposts = db(db.blog.public==True).select(db.blog.ALL, orderby=~db.blog.id, limitby=(0,10), cache=(cache.ram, 150), cacheable=True)
	
	return dict(posts=posts, pagination=pag, records=records, items_per_page=items_per_page, lastposts=lastposts)
Exemplo n.º 26
0
def search(page_num=1):
    """Search user query."""
    offset = (page_num - 1) * MAX_RESULTS

    query = request.args.get('q').strip()  # ensure query is some kind of string

    results = lookup(query=query, offset=offset, max_results=MAX_RESULTS)

    num_results = results.pop()  # total matches on query string
    headlines = results  # list of headlines

    if not headlines[0]:
        headlines = None

    pages = Pagination(page_num, (num_results // MAX_RESULTS) + 1, 4, 4)

    return render_template("search.html", query=query, headlines=headlines,
                           num_results=num_results, pages=pages.paginate())
Exemplo n.º 27
0
def search_view(query, page):
    settings = util.get_current_settings()

    query_str = "\'" + query + "\'"  # the quotation marks are absolutely necessary for a pg tsquery with multiple words

    if current_user.is_authenticated:
        if current_user.admin:
            posts_matched_content = Post.select()\
                .where((Match(Post.content, query_str) == True))
            posts_matched_title = Post.select()\
                .where((Match(Post.title, query_str) == True)
                       & (Match(Post.content, query_str) == False))
            posts_matched_tag = Post.select().join(PostTag).join(Tag)\
                .where((Match(Tag.name, query_str) == True)
                       & (Match(Post.title, query_str) == False)
                       & (Match(Post.content, query_str) == False))

    else:
        posts_matched_content = Post.select()\
                .where((Post.published == True)
                       & (Match(Post.content, query_str) == True))
        posts_matched_title = Post.select()\
                .where((Post.published == True)
                       & (Match(Post.title, query_str) == True)
                       & (Match(Post.content, query_str) == False))
        posts_matched_tag = Post.select().join(PostTag).join(Tag) \
                .where((Post.published == True)
                       & (Match(Tag.name, query_str) == True)
                       & (Match(Post.title, query_str) == False)
                       & (Match(Post.content, query_str) == False))

    posts_matched = posts_matched_content + posts_matched_title + posts_matched_tag

    number_of_matched_posts = posts_matched.count()

    posts_matched = posts_matched.paginate(page, settings.posts_per_page)

    posts_with_tags = []
    for post in posts_matched:
        tags = Tag.select().join(PostTag)\
            .where(PostTag.post == post).order_by(Tag.name)
        posts_with_tags.append([post, tags])

    pages = Pagination(page, settings.posts_per_page, number_of_matched_posts,
                       7)

    if not number_of_matched_posts == 0:
        return render_template('search_view.html',
                               posts_with_tags=posts_with_tags,
                               pages=pages,
                               query=query,
                               current=search_view)

    else:
        notice = "No search results for " + str(query_str) + " !"
        return render_template('notice.html', notice=notice)
Exemplo n.º 28
0
Arquivo: views.py Projeto: qgreg/puppy
def adopterList(page=1):
	count = session.query(Adopter).count()
	offset = (page - 1) * ADOPTER_POST_PER_PAGE
	print count
	if count > 1:
		adopter = session.query(Adopter).order_by(Adopter.id).slice(offset, offset + ADOPTER_POST_PER_PAGE)
		paginate = Pagination(page, ADOPTER_POST_PER_PAGE, count)
		return render_template('adopterlist.html', adopter = adopter, page = page, paginate = paginate)
	else:
		return "Zero"
Exemplo n.º 29
0
def index(pageNumber=None):
	if not pageNumber:
		pageNumber = 0
	repoHashes = r.lrange('REPOS',0,-1)
	tags  = r.lrange('TAGS',0,-1)
	finalNames = []
	for rHash in repoHashes[(pageNumber*10):(pageNumber*10)+10]:
		finalNames.append({'name':r.get('REPO:%s'%rHash),'hash':rHash,'tags':r.lrange('REPO:%s:TAGS'%rHash,0,-1)})
	print pageNumber
	pagination = Pagination(pageNumber, 10, len(repoHashes))
	return render_template('index.html',repos=finalNames,tags=tags,pagination=pagination)
Exemplo n.º 30
0
def results(query_condition, page):
    # 按文章题目搜索
    # @See: http://docs.mongoengine.org/guide/querying.html#limiting-and-skipping-results
    start = (page - 1) * number_per_page
    limit = page * number_per_page
    articles = Article.objects(
        title__contains=query_condition).order_by('-create_time')[start:limit]
    count = Article.objects(title__contains=query_condition).count()
    page_obj = Pagination(page, number_per_page, count)
    return render_template('results.html',
                           articles=articles,
                           pagination=page_obj)
Exemplo n.º 31
0
def users(page=1):
    per_page = 5
    message = None
    if 'message' in request.args:
        message = request.args['message']
    user_s = UserService()
    count = user_s.count_all_users()
    users = user_s.select_page_users(page, per_page)
    if not users and page != 1:
        abort(404)
    pagination = Pagination(page, per_page, count)
    return render_template('users.html', pagination=pagination, users=users, message=message)