def get_results_empresas(self, term, page, limit): offset = int((page-1) * limit) filters = [] if term != 'none': filters.append( or_(models.Empresa.razon_social.ilike('%' + term + '%'), models.Empresa.ruc.ilike('%' + term + '%')) ) results = db.query( models.Empresa ).filter( or_(*filters) ).limit(limit).offset(offset) count = db.query(func.count(models.Empresa.id) ).filter(and_(*filters) ).scalar() pagination = Pagination(page=page, total=count, per_page=limit) pagination.index = offset pagination.count = count return [results, pagination]
def get_results_entidades(self, term, page, limit): offset = int((page-1) * limit) filters = [] if term != 'none': filters.append( models.EntidadGobierno.nombre.ilike('%'+term+'%') ) results = db.query( models.EntidadGobierno.id, models.EntidadGobierno.nombre, models.TipoGobierno.tipo ).filter( and_(*filters) ).join( models.TipoGobierno ).order_by( models.EntidadGobierno.nombre.desc() ).limit(limit).offset(offset) count = db.query(func.count(models.EntidadGobierno.id) ).filter( and_(*filters) ).scalar() pagination = Pagination(page=page, total=count, per_page=limit) pagination.index = offset pagination.count = count return [results, pagination]
def get_results_irregulares(self, term, page, limit): filters = [or_(models.Contrataciones.etiqueta_fecha == 'irregulares', models.Contrataciones.etiqueta_fecha == 'cercanas')] if term != 'none': filters.append( and_(models.Contrataciones.descripcion.ilike('%'+term+'%')) ) offset = int((page-1) * limit) results = db.query( models.Contrataciones.id, models.Contrataciones.proceso, models.Contrataciones.objeto_pro, models.Contrataciones.fecha_pub, models.Contrataciones.fecha_bue_pro, models.Contrataciones.modalidad_sel, models.Contrataciones.tipo_moneda, models.Contrataciones.monto, models.Contrataciones.valor_ref, models.Contrataciones.descripcion, models.EntidadGobierno.id.label("eid"), models.EntidadGobierno.nombre, models.Contrataciones.empresa_id, models.Empresa.razon_social, models.Empresa.ruc, models.Contrataciones.detalle_contrato, models.Contrataciones.detalle_seace, models.Contrataciones.etiqueta_fecha, models.Contrataciones.etiqueta_monto ).join( models.Empresa, models.EntidadGobierno ).filter( and_(*filters) ).order_by( models.Contrataciones.fecha_bue_pro.desc() ).limit(limit).offset(offset) count = db.query(func.count(models.Contrataciones.id) ).filter(and_(*filters) ).scalar() pagination = Pagination(page=page, total=count, per_page=limit) pagination.index = offset pagination.count = count return [results, pagination]
def index(page=1): questions, count = dao.select(QUESTION_COLL, {}, limit=PAGE_SIZE, skip=(page - 1) * PAGE_SIZE) for question in questions: imgs = [] for answer in question['answers']: the_ans = dao.select_one(ANSWER_COLL, {'_id': answer}) imgs.extend(the_ans['imgs']) if len(imgs) >= 5: break question['imgs'] = imgs[:5] data = { 'active': 'index', 'title': u'知乎钓鱼图 - 第 %s 页' % page, 'questions': questions, 'pagination': Pagination(page=page, per_page=PAGE_SIZE, total=count, css_framework='bootstrap3') } return render_template('index.html', **data)
def display_repos_info(): counts = db.session.query( db.func.count('*')).select_from(RepoInfo).scalar() per_page = 5 search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 offset = (page - 1) * per_page sql = 'select * from repos_info limit {},{}'.format(offset, per_page) repos = db.session.query(RepoInfo).from_statement(db.text(sql)).all() pagination = Pagination(page=page, link_size='sm', total=counts, record_name='repos', per_page=per_page, bs_version=3, format_total=True, format_number=True, show_single_page=False) return render_template('list-repo.html', repos=repos, pagination=pagination, page=page, per_page=per_page)
def company_listings(): page = int(request.args.get('page', 1)) per_page = request.args.get('per_page', 10) total_companies = len(COMPANIES) company_names = [c['name'] for c in COMPANIES] page_company_names = fetch_ten(company_names, page, per_page) if not company_names and page != 1: abort(404) pagination = Pagination(css_framework='bootstrap3', link_size='sm', page=page, per_page=per_page, total=total_companies, record_name='companies') log_request(request) return render_template('company_listings.html', company_names=page_company_names, page=page, per_page=per_page, pagination=pagination)
def recommendations(): global DF, DF_FILTERED, COUNTRIES, PAGES try: if request.method == 'POST' and request.form['url'] is not None: url = str(request.form['url']) recommendation = user_recommendations(url) DF = recommendation.cosine_similarity() DF_FILTERED = DF page = 1 COUNTRIES = init_filters(DF) else: page = int(request.args.get('page', 1)) PAGES = DF_FILTERED.shape[0] i_end = page * 10 i_start = i_end - 10 df_subset = DF_FILTERED[i_start:i_end] pagination = Pagination(page=page, total=PAGES, css_framework='foundation') return render_template('search.html', df=df_subset, pagination=pagination, countries=COUNTRIES) except ValueError: return render_template('input.html', msg='Oops! Please enter a Linkedin profile url')
def index(): index_form = request.form current_app.logger.info(request.form) search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 device_obj = Device() total = device_obj.get_count() devices = device_obj.paginate(page, 8).items pagination = Pagination(css_framework='bootstrap3', link_size='sm', show_single_page=False, page=page, per_page=8, total=total, search=search, record_name='devices', format_total=True, format_number=True) template_data = { 'form': index_form, 'devices': devices, 'pagination': pagination } return render_template("/device/index.html", **template_data)
def show_movies(): total = current_app.config['TOTAL_MOVIES'] if not total: total = current_app.config['MOVIES_COLLECTION'].find().count() page, per_page, offset = get_page_items() if page * per_page > total: movies_info = "" else: movie_cursor = current_app.config['MOVIES_COLLECTION'].find({}, { "_id": 0 }).skip(offset).limit(per_page) genre_info = current_app.config['GENRE_COLLECTION'].find_one( {}, {"_id": 0}) movies_info = list([]) for item in movie_cursor: item_dict = dict({}) item_dict["id"] = int(item["id"]) item_dict["title"] = item["title"] genre_desc = "" for x in item["genre"]: desc = genre_info[str(x)] genre_desc += desc + "|" item_dict["genre"] = genre_desc[:-1] movies_info.append(item_dict) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap3', record_name="movies_info") return render_template('movies.html', total=total, movies=movies_info, page=page, per_page=per_page, pagination=pagination)
def index(): ''' PURPOSE: display relevant articles on site. Filter content via checkboxes at top of page if POST request is found INPUT: None (access global variables DF, DF_SUBSET, PAGES) OUTPUT: html (flask obj) - rendered html to display content ''' global DF_SUBSET, PAGES, DF if request.method == 'POST': filtr = request.form.getlist('checkboxes') if len(filtr) != 0: DF_SUBSET = DF[(DF[filtr] == 1).stack().sum(level=0)] \ .reset_index(drop=True) else: DF_SUBSET = DF page = 1 PAGES = len(DF_SUBSET) else: page = int(request.args.get('page', 1)) i_end = page * 10 i_start = i_end - 10 articles = DF_SUBSET[i_start:i_end].to_dict('index') pagination = Pagination(page=page, total=PAGES, css_framework='foundation') return flask.render_template('index.html', articles=articles, pagination=pagination)
def contracts_for_cnpj(cnpj): cnpj = "{}.{}.{}/{}-{}".format(cnpj[0:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14]) # contratos = db.session.query(Contrato).filter(Contrato.cnpj == cnpj).all() page = int(request.args.get('page', 1)) per_page_num = 10 try: contratos_query = db.session.query(Contrato).filter( Contrato.cnpj == cnpj) contratos = contratos_query.offset( (page - 1) * per_page_num).limit(per_page_num).all() count = contratos_query.count() pagination = Pagination(page=page, per_page=per_page_num, total=count, found=count, bs_version=3, search=True, record_name='contratos') return render_template('contratos-cnpj.html', contratos=contratos, pagination=pagination, count=count, filter_info=u"Fornecedor", filter_value=cnpj) except TemplateNotFound: abort(404)
def log(): flag = current_user.is_administrator(g.user) if flag is True: p = Page() record = p.GetRecord() records = {} records = OrderedDict() total = len(record) page = request.args.get('page', 1, type=int) per_page = 10 keys = record.keys() offset = (page - 1) * per_page for i in range(len(keys)): if i < per_page and (offset + i) < len(keys): records[keys[offset + i]] = record[keys[offset + i]] else: break pagination = Pagination(css_framework='bootstrap3', link_size='sm', show_single_page=False, page=page, per_page=per_page, total=total, format_total=True, format_number=True) return render_template('log.html', records=records, page=page, per_page=per_page, pagination=pagination) else: abort(403)
def show_user_page(user_id): if request.method == 'GET': if not session.get('logged_in'): return "You are not logged in" user = dbOps.get_user_by_ID(user_id) if user: sorting = request.args.get('sorting') if sorting == 'OldestFirst': sorting = 'OldestFirst' posts = dbOps.get_oldest_first_posts_by_user(user) else: sorting = 'MostRecent' posts = dbOps.get_most_recent_posts_by_user(user) page, per_page, offset = get_page_items(5) pagination = Pagination(page=page, total=len(posts), search=False, record_name='posts', per_page=5, css_framework='foundation') return render_template('user_page.html', user_id=user_id, posts=posts[offset:offset + per_page], pagination=pagination, sorting=sorting) else: return "No user account associated with that user" if request.method == 'POST': return redirect(url_for('create_post', user_id=user_id))
def contracts_for_evento(evento): page = int(request.args.get('page', 1)) per_page_num = 10 try: contratos_query = db.session.query(Contrato).filter( Contrato.evento == evento) contratos = contratos_query.offset( (page - 1) * per_page_num).limit(per_page_num).all() count = contratos_query.count() pagination = Pagination(page=page, per_page=per_page_num, total=count, found=count, bs_version=3, search=True, record_name='contratos') return render_template('contratos-orgao.html', contratos=contratos, pagination=pagination, count=count, filter_info="Evento", filter_value=evento) except TemplateNotFound: abort(404)
def display_deploy_info(): counts = db.session.query( db.func.count('*')).select_from(DeployInfo).scalar() print counts per_page = 10 search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 offset = (page - 1) * per_page sql = 'select * from deploy_info order by deploy_info.deploy_date desc limit {},{}'.format( offset, per_page) deploy = db.session.query(DeployInfo).from_statement(db.text(sql)).all() pagination = Pagination(page=page, link_size='sm', total=counts, record_name='deploy', per_page=per_page, bs_version=3, format_total=True, format_number=True, show_single_page=False) return render_template('list-deploy-log.html', deploy=deploy, pagination=pagination, page=page, per_page=per_page)
def index(): index_form = request.form current_app.logger.info(request.form) search = False if not current_user.is_admin: return redirect('/') q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 user_obj = User() total = user_obj.get_count() users = user_obj.paginate(page, 8).items pagination = Pagination(css_framework='bootstrap3', link_size='sm', show_single_page=False, page=page, per_page=8, total=total, search=search, record_name='users', format_total=True, format_number=True) template_data = { 'form': index_form, 'users': users, 'pagination': pagination } return render_template("/user/index.html", **template_data)
def search_results(url): score = BiasScoring(url) score.parallelize_articlize() ''' Liberal/Conservative analysis currently unavailable on github: predict = Predict() pred, articles = predict.featurize_predict(score.articles) i=0 for k, v in score.article_rank.items(): score.article_rank[k]['prediction'] = pred[i] print score.article_rank[k]['prediction'] i+=1 ''' page = int(request.args.get('page', 1)) pagination = Pagination(page=page, total=len(score.article_rank), search=False, record_name='score.article_rank', css_framework='foundation') return render_template('search.html', data=score.article_info, pagination=pagination)
def search(): global entries page = 1 if not session.get('logged_in'): abort(401) if request.method == 'POST': entries = [] keyword = request.form['Text'] flash('The matched result for ' + keyword + ' is:') entries = sphinx_search(keyword) else: try: page = int(request.args.get('page', 1)) except ValueError: page = 1 page_entries = get_entry_for_page(page, 10, entries) #print page_entries pagination = Pagination(page=page, total=len(entries), search=False, record_name='result') url_file = [] for entry in page_entries: #print download(entry) url_file.append(download(entry)) return render_template('show_entries.html', entries=url_file, pagination=pagination, show_result=True)
def wf_metadata_find(key, value, state): db = lp.workflows try: value = int(value) except ValueError: pass q = {'metadata.{}'.format(key): value} state_mixin = {} if state == "total" else {"state": state} q.update(state_mixin) wf_count = lp.get_wf_ids(query=q, count_only=True) if wf_count == 0: abort(404) elif wf_count == 1: doc = db.find_one(q, {'nodes': 1, '_id': 0}) fw_id = doc['nodes'][0] return redirect(url_for('wf_details', wf_id=fw_id)) else: try: page = int(request.args.get('page', 1)) except ValueError: page = 1 rows = list(db.find(q).sort([('_id', DESCENDING)]).\ skip(page - 1).limit(PER_PAGE)) for r in rows: r["fw_id"] = r["nodes"][0] pagination = Pagination(page=page, total=wf_count, record_name='workflows', per_page=PER_PAGE) all_states = STATES return render_template('wf_metadata.html', **locals())
def search(): if request.method == 'POST': search_value = request.form.getlist('search')[0] original_search_value = search_value search_value = quote_plus(search_value) #print search_value if (len(request.form.getlist('page')) > 0): result = query(search_value, int(request.form.getlist('page')[0])) else: result = query(search_value) if is_EIN(search_value): org = result['organization'] # redirect ein = parse_EIN(search_value) return redirect(url_for('ein_results', ein=ein)) else: filings = result['filings'] num_results = result['total_results'] #print 'Search yielded ' + str(num_results) + ' result(s).' results_for_html = [] for i in range(0, len(filings)): org = filings[i]['organization'] result_for_html = { 'name': org['name'].title(), 'ein': org['ein'], 'city': org['city'].title(), 'state': org['state'], 'tax_prd': filings[i]['tax_prd'] } added_already = False for i in range(0, len(results_for_html)): if (results_for_html[i]['ein'] == result_for_html['ein']): added_already = True break if (not added_already): results_for_html.append(result_for_html) if (len(request.form.getlist('page')) > 0): page = int(request.form.getlist('page')[0]) else: page = 1 pagination = Pagination(page=page, total=num_results, search=False, per_page=RESULTS_PER_PAGE) return render_template('index.html', results=results_for_html, pagination=pagination, no_result=len(results_for_html) == 0, search_value=original_search_value) return render_template('index.html')
def shout(): session["currentpage"] = "Shout Box" search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 db = get_cursor() start = 0 per_page = 2 if page == 1: start = 0 else: start = (page - 1) * per_page sql = 'select * from AnonymousPosts order by Date desc limit %s,%s' % ( start, per_page) db.execute(sql) posts = db.fetchall() db.execute("commit") activity = [] comments = [] i = 0 for post in posts: sql = 'select activity from like_history where sno=%s and username="******"' % ( post[0], app.config['USERNAME']) db.execute(sql) result = db.fetchone() db.execute("commit") if result is None: like = -1 else: like = int(result[0]) activity.append(int(like)) sql = 'select * from comments where sno=%s order by date' % (post[0]) db.execute(sql) comments.append(db.fetchall()) i = i + 1 query = 'select Count(*) from anonymousposts' db.execute(query) total = int(db.fetchone()[0]) db.execute("commit") pagination = Pagination(page=page, per_page=per_page, total=total, search=search, record_name='posts', bs_version=3) return render_template('shout/screen.html', posts=posts, UName=app.config['USERNAME'], activity=activity, pagination=pagination, comments=comments) #show_entries
def get(self, cid): channels = ChannelModel.query.all() channel = ChannelModel.query.get(cid) pager = Pagination(bs_version=3, page=self.page, total=channel.articles.count()) return render_template('www/channel.html', channels=channels, channel=channel, pager=pager)
def tags(tag, page=1): page = int(page) count_news = News.objects(category=tag).count() posts = News.objects(category=tag).order_by('-date').skip((page - 1) * NEWS_ON_PAGE).limit(NEWS_ON_PAGE) pagination = Pagination(page=page, per_page=NEWS_ON_PAGE, total=count_news, record_name='News', format_total=True, format_number=True) return render_template("news.html", posts=posts, pagination=pagination, title="Cryptocurrency news today")
def update(): p = Page() title = [] u = User() title = p.GetTitles() titles = [] pushtime = u.GetPushtime(g.user) deltime = u.GetDeltime(g.user) jsondata = request.get_json() total = len(title) page = request.args.get('page', 1, type=int) per_page = 10 offset = (page - 1) * per_page for i in range(len(title)): if i < per_page and (offset + i) < len(title): titles.append(title[offset + i]) else: break pagination = Pagination(css_framework='bootstrap3', link_size='sm', show_single_page=False, page=page, per_page=per_page, total=total, format_total=True, format_number=True) if request.method == 'POST' and jsondata['action'] == 'post': if pushtime is not '0': title = jsondata['title'] flag = p.Break(title) if flag == True: p.RecordUpdate(title, current_user.id, '推送') pass else: abort(403) else: abort(403) if request.method == 'POST' and jsondata['action'] == 'del': if deltime is not '0': title = jsondata['title'] flag = p.Delete(title) if flag == True: p.RecordUpdate(title, current_user.id, '删除') pass else: abort(403) return render_template('update.html', titles=titles, current_time=datetime.utcnow(), pushtime=pushtime, deltime=deltime, page=page, per_page=per_page, pagination=pagination)
def get(self, cid): channel = ChannelModel.query.get(cid) query = ChannelModel.get_channel_query('cn') pager = Pagination(bs_version=3, page=self.page, total=channel.articles.count()) return render_template('www/channel.html', channels=query.all(), channel=channel, language=channel.language, pager=pager)
def showresult(entries): try: page = int(request.args.get('page', 1)) except ValueError: page = 1 pagination = Pagination(page=page, total=len(entries), search=False, css_framework='foundation') return render_template('show_entries.html', entries=entries, pagination=pagination, show_result=True)
def index(page): user = getMe() condition = {'userId': ObjectId(user.get_id())} db_blogs = mongo.db.blogs.find(condition).sort("postTime", DESCENDING) pageSize = app.config['PAGE_SIZE'] skipNum = (page - 1) * pageSize blogCollection = db_blogs.skip(skipNum).limit(pageSize) blogs = list(blogCollection) for blog in blogs: blog.setdefault('user', user) pagination = Pagination(page=page, total=db_blogs.count(), per_page=pageSize, bs_version='3') return render_template('index.html', blogs=blogs, pagination=pagination)
def show(): all_pages = request.args.get('all_pages', '') search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 questions_all = [] key_words = '' # 搜索关键字 if request.method == 'POST': key_words = request.form.get('key_word') if key_words: indexs = db.index.find_one({key_words: {'$exists': True}}) if indexs: ids = [ObjectId(id) for id in indexs[key_words].keys()] questions_all = db.zhihu.find({'_id': {"$in": ids}}).sort('answer_count', -1) if not questions_all: if all_pages: questions_all = db.zhihu.find().sort('answer_count', -1) else: questions_all = db.zhihu.find({'created': {"$gt": days_ago}}).sort('answer_count', -1) #如果最近几天没有数据(没有爬数据),则显示前50条数据 if not questions_all.count(): questions_all = db.zhihu.find().sort('created', -1).limit(50) pagination = Pagination(page=page, total=questions_all.count(True), search=search, record_name='questions') pagination.per_page = 30 #每页30个条目 #pagination插件有问题,这里参考boostrap分页的写法 links = str(pagination.links).replace('<div class="pagination"><ul>', '<div><ul class="pagination">') questions = questions_all[(page-1)*pagination.per_page:page*pagination.per_page] return render_template('base.html', questions=questions, pagination=pagination, links=links, key_words=key_words)
def wf_states(state): db = lp.workflows q = {} if state == "total" else {"state": state} wf_count = lp.get_fw_ids(query=q, count_only=True) try: page = int(request.args.get('page', 1)) except ValueError: page = 1 rows = list(db.find(q).sort([('_id', DESCENDING)]).skip(page - 1).limit(PER_PAGE)) for r in rows: r["fw_id"] = r["nodes"][0] pagination = Pagination(page=page, total=wf_count, record_name='workflows', per_page=PER_PAGE) all_states = STATES return render_template('wf_state.html', **locals())
def fw_states(state): db = lp.fireworks q = {} if state == "total" else {"state": state} fw_count = lp.get_fw_ids(query=q, count_only=True) try: page = int(request.args.get('page', 1)) except ValueError: page = 1 rows = list(db.find(q, projection=["fw_id", "name", "created_on"]).sort([('_id', DESCENDING)]).skip(page - 1).limit( PER_PAGE)) pagination = Pagination(page=page, total=fw_count, record_name='fireworks', per_page=PER_PAGE) all_states = STATES return render_template('fw_state.html', **locals())
def guobianyulist1(cateen=''): pagesize = 10 page = int(request.args.get('page', 0)) #获取当前页面页数 _guobianyulist, _count = dw.get_guobianyu_by_cateen_page1( cateen, page, pagesize) pagination = Pagination(css_framework='bootstrap3', total=_count, prev_label=u"上一页", next_label=u"下一页", inner_window=8, per_page=pagesize, page=page) return render_template('admin/guobianyulist1.html', guobianyulist=_guobianyulist, pagination=pagination)
def getList(model): """ 获取数据模型的列表 :param model: :return: """ global _page_idx, _page, N_PAGE if model == DataElement: model_name = u'数据元管理' elif model == MemberMod: model_name = u'员工列表' elif model == ProjectMod: model_name = u'项目列表' elif model == ProductMod: model_name = u'产品列表' elif model == TaskMod: model_name = u'任务列表' elif model == EnginerringMod: model_name = u'工程列表' elif model == DeliveryMod: model_name = u'产品交付列表' elif model == UpFileMod: model_name = u'文件上传日志' _rec = getAll(model) page = _page_idx[_page] _index = (page - 1) * N_PAGE _next = _index + N_PAGE if _next > len(_rec): """ 2015.9.15 by shenwei @chengdu 当本页面内容被删完时,应转到上一页 """ if len(_rec[_index:]) == 0 and page > 1: page -= 1 _page_idx[_page] = page _posts = _rec[_index:] else: _posts = _rec[_index:_next] pagination = Pagination(page=page, total=len(_rec), record_name=model_name, css_framework='foundation') return pagination, _posts
def door2door(place): page = h.safeint(request.args.get('page', 1), default=1, minvalue=1) total = place.get_door2door_count() limit = 50 pagination = Pagination(total=total, page=page, per_page=limit, bs_version=3, prev_label="« Prev", next_label="Next »") entries = place.get_door2door_entries(limit=limit, offset=(page - 1) * limit) return render_template("door2door.html", place=place, entries=entries, pagination=pagination)
def nobody(page=1): imgs = dao.get_qbcr_imgs(page) data = { 'active': 'nobody', 'title': u'佚名图集 - 第 %s 页' % page, 'images': imgs, 'pagination': Pagination(page=page, per_page=PAGE_SIZE, total=dao.get_qbcr_count(), css_framework='bootstrap3') } return render_template('yiming.html', **data)