def filter(filter_type, direction): """filter: * Checks for selected sort order * Sets the order in which the data will display on main page. * Displays data in defined order with pagination. \n Args: 1. filter_type(str): Targeted field within db collection. 2. direction(str): Direction of db sort order (ascending or descending). \n Returns: * Template displaying works from db in respective sort order. """ if direction == 'ascending': works = list(mongo.db.works.find().sort(filter_type, 1)) # pagination def get_works(offset=0, per_page=9): return works[offset: offset + per_page] page, per_page, offset = get_page_args( page_parameter='page', per_page_parameter='per_page' ) per_page = 9 total = len(works) pagination_works = get_works(offset=offset, per_page=per_page) pagination = Pagination( page=page, per_page=per_page, total=total, css_framework='bootstrap4' ) return render_template( "works.html", works=pagination_works, page=page, per_page=per_page, pagination=pagination ) works = list(mongo.db.works.find().sort(filter_type, -1)) # pagination def get_works(offset=0, per_page=9): return works[offset: offset + per_page] page, per_page, offset = get_page_args( page_parameter='page', per_page_parameter='per_page' ) per_page = 15 total = len(works) pagination_works = get_works(offset=offset, per_page=per_page) pagination = Pagination( page=page, per_page=per_page, total=total, css_framework='bootstrap4' ) return render_template( "works.html", works=pagination_works, page=page, per_page=per_page, pagination=pagination )
def main(): global search_input, Index, bookkeeping, total if Index == {}: load_index() s = run_search(search_input) total, total_links, total_tokens = s['tr'], s['tl'], s['tt'] page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') if request.method == 'POST': session['user'] = os.urandom(8) search_input = request.form['search_input'] s = run_search(search_input) total, total_links, total_tokens = s['tr'], s['tl'], s['tt'] page, per_page, offset = get_page_args(page_parameter='1', per_page_parameter='per_page') pagination_links = get_results(offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=len(total), css_framework='bootstrap4') return render_template('index.html',search=search_input, links=total_links, tokens=total_tokens, all_tokens=N_tokens, all_documents=N_documents, results=pagination_links, per_page=per_page, page=page, pagination=pagination)
def product_list(): colname = ['編號','名稱','分類','價格','數量','刪除','編輯'] table_cols = [Product.id,Product.name,Product_Class.name,Product.price,Product.counts] sort_col_index = -1 sort_type = request.args.get('type') sort_col_name = request.args.get('col') if sort_col_name: try: sort_col_index = colname.index(sort_col_name) except Exception as err: sort_col_index = -1 print('sort_col_index err:',err) if sort_type == 'desc' and sort_col_index in range(0,5) : rows = [[p.id, p.name, c.name, p.price, p.counts] for p, c in db.session.query(Product, Product_Class). order_by(desc(table_cols[sort_col_index])). filter(Product.class_id == Product_Class.id).all() ] elif sort_type == 'asc' and sort_col_index in range(0,5): rows = [[p.id, p.name, c.name, p.price, p.counts] for p, c in db.session.query(Product, Product_Class). order_by(asc(table_cols[sort_col_index])). filter(Product.class_id == Product_Class.id).all() ] else: rows = [[p.id, p.name, c.name, p.price, p.counts] for p, c in db.session.query(Product, Product_Class). filter(Product.class_id == Product_Class.id).all() ] #debug print(rows[0]) #分頁 (pip install -U flask-paginate) page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(rows) pagination = Pagination(page=page, per_page=per_page, total=total, bs_version=4, css_framework='bootstrap') print('page args:',get_page_args(page_parameter='page', per_page_parameter='per_page')) pagination_rows = rows[offset: offset + per_page] return render_template('product_list.html', colname=colname, rows=pagination_rows, page=page, per_page=per_page, pagination=pagination)
def decklist(): form = Deckform() if form.validate_on_submit(): session['freeword'] = form.freeword.data session['red'] = form.red.data session['white'] = form.white.data session['green'] = form.green.data session['blue'] = form.blue.data session['black'] = form.black.data page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') query = get_query() total = mongo.db.decks.find(query).count() pagination_decks = get_decks(offset=offset, per_page=per_page, query=query) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template( 'decklist.html', decks=pagination_decks, page=page, per_page=per_page, pagination=pagination, form=form, total=total, ) page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') query = get_query() total = mongo.db.decks.find(query).count() pagination_decks = get_decks(offset=offset, per_page=per_page, query=query) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('decklist.html', decks=pagination_decks, page=page, per_page=per_page, pagination=pagination, form=form, total=total)
def viewPost(): if request.method == 'GET': page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') bds = batdongsan.find().sort("_id",-1) bds = bds.skip(offset).limit(per_page) bds = list(bds) total = batdongsan.count() pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') if 'user' in session: user = loads(session["user"]) postWish = user["postWish"] return render_template('listHouse.html', user=loads(session['user']), bds=bds, postWish= postWish, page=page, per_page=per_page, pagination=pagination) else: return render_template('listHouse.html', bds=bds, postWish = [], page=page, per_page=per_page, pagination=pagination) else: sq_from = request.form['sq_from'] sq_to = request.form['sq_to'] pr_from = request.form['pr_from'] pr_to = request.form['pr_to'] category = request.form['category'] location = request.form['location'] page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') bds = batdongsan.find({"$and" : [{"type" : {"$regex": category}}, {"district" : {"$regex": location}}, {"square" : {"$lt": float(sq_to)}}, {"square" : {"$gt": float(sq_from)}}, {"price" : {"$lt": float(pr_to)}}, {"price": {"$gt" : float(pr_from)}}]}).sort("_id",-1) bds = bds.skip(offset).limit(per_page) bds = list(bds) total = batdongsan.count({"$and" : [{"type" : {"$regex": category}}, {"district" : {"$regex": location}}, {"square" : {"$lt": float(sq_to)}}, {"square" : {"$gt": float(sq_from)}}, {"price" : {"$lt": float(pr_to)}}, {"price": {"$gt" : float(pr_from)}}]}) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') if 'user' in session: user = loads(session["user"]) postWish = user["postWish"] return render_template('listHouse.html',user=loads(session['user']), bds=bds, postWish=postWish, page=page, per_page=per_page, pagination=pagination) else: return render_template('listHouse.html', bds=bds, postWish=[], page=page, per_page=per_page, pagination=pagination)
def test_get_page_args_works_inside_of_request_context(self): """get_page_args raises no error if called with a request ctx.""" with self.app.test_request_context('/'): self.app.preprocess_request() get_page_args() page_param, per_page_param = get_page_args(page_parameter='p', for_test=True) assert page_param == 'p' assert per_page_param == 'per_page' page_param, per_page_param = get_page_args(per_page_parameter='pp', for_test=True) assert page_param == 'page' assert per_page_param == 'pp'
def test_get_page_args_works_inside_of_request_context(self): """get_page_args raises no error if called with a request ctx.""" with self.app.test_request_context("/"): self.app.preprocess_request() get_page_args() page_param, per_page_param = get_page_args(page_parameter="p", for_test=True) assert page_param == "p" assert per_page_param == "per_page" page_param, per_page_param = get_page_args(per_page_parameter="pp", for_test=True) assert page_param == "page" assert per_page_param == "pp"
def search(): global name # if request.method == 'POST': name = request.form.get('jiancharen') global danwei danwei = request.form.get('jianchadanwei') print(name) print(danwei) global u if u == None: sql = ("select * from {} where 检查人 LIKE '%{}%' and 录入科室 LIKE '%{}%'". format(table_name, name, danwei)) cursor.execute(sql) u = cursor.fetchall() page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(u) print(total) pagination_users = get_users(offset=offset, per_page=20) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template( 'all-admin-datalist.html', users=pagination_users, page=page, per_page=per_page, pagination=pagination, ) else: page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(u) print('total') pagination_users = get_users(offset=offset, per_page=20) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template( 'all-admin-datalist.html', users=pagination_users, page=page, per_page=per_page, pagination=pagination, )
def tiendainglesa(): listacolecciones = data.list_colecciones_tiendainglesa() Objetos = [] for coleccion in listacolecciones: collection = data.display_tiendainglesa(coleccion) Objetos += collection.find({}) def get_objetos(offset=0, per_page=25): return Objetos[offset:offset + per_page] page, a, offset = get_page_args(page_parameter='page') per_page = 20 total = len(Objetos) pagination_objetos = get_objetos(offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template( 'tiendainglesa.html', objetos=pagination_objetos, page=page, per_page=per_page, pagination=pagination, )
def get_product_by_category(): category_query_id = request.args.get('category') if category_query_id is None: abort(404) try: id_category = int(category_query_id) except ValueError: abort(404) goods_result = Good.query.filter_by(category_id=id_category).all() page, per_page, offset = get_page_args( page_parameter='page', per_page=current_app.config['PAGES_ON_VIEW']) good_items = get_items_per_page(goods_result, offset=offset, per_page=per_page) total_goods = len(goods_result) pagination = Pagination(page=page, per_page=per_page, total=total_goods, css_framework='bootstrap4') return render_template( 'goods/good_list.html', items=good_items, page=page, per_page=per_page, pagination=pagination, )
def delete(): if request.method == 'POST': for key, value in request.form.items(): if key == "button": if value == "get": check_data_temp() data = get_file() if data: data_temp.append(data) return redirect(request.url) else: delete_file(value) if value in data_temp[0]: data_temp[0].remove(value) os.remove(os.path.join(app.config['UPLOAD_FOLDER'], value)) return redirect(request.url) if data_temp: data = data_temp[0] page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page', ) pagination_data = get_per_data(data, offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=len(data), css_framework='bootstrap4') return render_template('delete.html', data=pagination_data, pagination=pagination) return render_template('delete.html')
def product_management(): """ A view to return all the products and sort and paginates them. Gets the sort search perameter. Code is from https://www.kite.com/python/ answers/ how-to-get-parameters-from-a-url-using-flask-in-python """ sort_by = request.args.get("sort") """ Sort method is from https://docs.mongodb.com/manual/reference/ method/cursor.sort/index.html """ if sort_by: products = list(mongo.db.products.find().sort(sort_items(sort_by))) else: products = list(mongo.db.products.find().sort('name', 1)) """ Pagination code is from https://gist.github.com/mozillazg/ 69fb40067ae6d80386e10e105e6803c9 """ page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page', per_page=10) pagination_products = paginate_items(products, offset, per_page) pagination = paginate(products, page, per_page) return render_template("product_management.html", page_title="Product Management", products=pagination_products, pagination=pagination)
def categories(catname, page=1): search = True if request.args.get('q') else False page, per_page, offset = get_page_args() category = Category.query.filter_by(slug=catname).first() pagination = Pagination(bs_version=3,page=page, per_page=per_page, total=category.medias.count(), search=search, record_name=category.name + ' medias') return render_template("medias.html", medias=sampling(category.medias.order_by(Media.rate.desc()), offset, per_page), pagination=pagination, title=catname.capitalize())
def AddQuestionNext(): # To find out the method of request, use 'request.method' if request.method == "GET": title = request.args.get("title") body = request.args.get("body") elif request.method == "POST": title = request.form['title'] body = str(request.form['body']) search_results = searchresults(title, 5) tags_list = list(predict_tags(title)) clean = re.compile('<.*?>') body = re.sub(clean, '', body) page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(search_results) p_questions = search_results[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total) return render_template('post_question_confirmation.html', similar_questions=p_questions, page=page, per_page=per_page, pagination=pagination, title=title, body=body, tags_list=tags_list)
def fb(): fbJobData = job.getJobData('fb_job') print(fbJobData) page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(fbJobData) pagination_jobData = [] for data in fbJobData: print(data) try: data['splitted_message'] = data['message'].split('\n') except: data['splitted_message'] = [] pagination_jobData.append(data) pagination_jobData = get_job(fbJobData, offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') print(pagination_jobData) return render_template( 'facebook.html', jobData=pagination_jobData, page=page, per_page=per_page, pagination=pagination, )
def list_company(): """ Display all companies in collection in card format Pagination inspiration - https://github.com/DarilliGames/flaskpaginate/blob/master/app.py """ page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') # Limit of 6 to be shown on each page per_page = 6 offset = (page - 1) * per_page # Get the total values to be used later total = mongo.db.companies.find().count() # Get all the companies from mongodb company = mongo.db.companies.find().sort('_id', -1) # Paginate the companies found paginatedCompanies = company[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='materialize') return render_template( 'all_companies_list.html', list_company=company, companies=paginatedCompanies, page=page, per_page=per_page, pagination=pagination, )
def index(): mintime = time.time() - 72 * 60 * 60 conn = sqlite3.connect("data/result.db") cur = conn.cursor() cur.execute( "SELECT result FROM resultdb_sciencenet WHERE updatetime>? \ UNION SELECT result from resultdb_solidot WHERE updatetime>?", (mintime, mintime)) result = cur.fetchall() rows = [] for r in result: rows.append(json.loads(r[0])) rows.sort(key=lambda i: i["date"], reverse=True) page, per_page, offset = get_page_args(page_parameter="page", per_page_parameter="per_page") pagination_rows = get_rows(rows=rows, offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=len(rows), css_framework="bootstrap4") return render_template("index.html", rows=pagination_rows, page=page, per_page=per_page, pagination=pagination)
def search_result(): # req = request range_limit = request.args['range_limit'] search_words = request.args['search_words'] page, per_page, offset = get_page_args() db_results = support.search(range_limit, search_words) results = db_results[0] counts = int(db_results[1]) pagination = Pagination(page=page, total=counts, search=True, record_name='users', css_framework=get_css_framework(), outerWindow=1, ecord_name="results", format_total=True, format_number=True, per_page=per_page) return render_template('search_result.html', search_words=search_words, results=results.skip(offset).limit(per_page), page=page, per_page=per_page, pagination=pagination, active_url='users-page-url', form=form)
def album_list(): """Show list of albums.""" # Return album objects using performers' and albums' relationship, ordering # results by album title. albums = Album.query.options( db.joinedload("performers").joinedload("albums")).order_by( 'album_title').all() page, per_page, offset = get_page_args(page_parameter="page", per_page_parameter="per_page") per_page = 100 offset = (page - 1) * per_page total = len(albums) pagination_albums = albums[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework="bootstrap4") return render_template("album_list.html", albums=pagination_albums, page=page, per_page=per_page, pagination=pagination)
def detail(page): # usertype = request.args.getlist('usertype') KEYWORD = request.args.get('keyword') ip = request.args.get('ip') searchtype = request.args.get('searchtype') searchtime = request.args.get('searchtime') starttime, endtime = search_time(searchtime) page, per_page, offset = get_page_args() print isinstance(ip, unicode) if searchtime is not None and isinstance(ip, unicode): starttime = starttime.split("'")[1] endtime = endtime.split("'")[1] total = db.session.query(IP_log).filter( db.and_(IP_log.created_at.between(starttime, endtime), IP_log.keyword.like('%' + KEYWORD + '%'))).count() users = db.session.query(IP_log).filter( db.and_(IP_log.created_at.between(starttime, endtime), IP_log.keyword.like('%' + KEYWORD + '%'))).limit( per_page).offset(offset).all() elif searchtime is not None and searchtype != 'none': starttime = starttime.split("'")[1] endtime = endtime.split("'")[1] total = db.session.query(IP_log).filter( db.and_(IP_log.created_at.between(starttime, endtime), IP_log.keyword.like('%' + KEYWORD + '%'), IP_log.click == searchtype)).count() users = db.session.query(IP_log).filter( db.and_(IP_log.created_at.between(starttime, endtime), IP_log.keyword.like('%' + KEYWORD + '%'), IP_log.click == searchtype)).limit(per_page).offset(offset).all() elif (not isinstance(ip, unicode) and ip != None): total = db.session.query(IP_log).filter(IP_log.ip == ip).count() users = db.session.query(IP_log).filter( IP_log.ip == ip).limit(per_page).offset(offset).all() else: total = db.session.query(IP_log).count() # users = db.session.query(IP_log).order_by(db.desc(IP_log.created_at)).limit(per_page).offset(offset).all() users = db.session.query(IP_log).order_by(db.desc( IP_log.created_at)).limit(per_page).offset(offset).all() pagination = get_pagination( page=page, per_page=per_page, total=total, record_name='iplog', format_total=True, format_number=True, ) return render_template( '/main/detail.html', users=users, page=page, per_page=per_page, pagination=pagination, )
def get(per_page, collection_id=None, collection_uuid=None): """Return details about the collection.""" elem = Collection.query.filter( or_(Collection.id == collection_id, Collection.uuid == collection_uuid)).first() if elem is None: abort(404) creator = User.query.filter(User.id == elem.creator_id).first() # Pagination page, per_page, offset = get_page_args() pagination = Pagination( page=page, total=len(elem.objects), css_framework="bootstrap4", search=False, record_name="objects", per_page=per_page, ) return render_template( "collection.html", collection=elem, objects=elem.objects[offset:][:per_page], creator=creator, pagination=pagination, )
def all_collections(): user = mongo.db.users.find_one({"username": session["user"]}) # Only admin can access this page if session['user'] == 'admin': # https://gist.github.com/mozillazg/69fb40067ae6d80386e10e105e6803c9 # https://stackoverflow.com/questions/27992413/how-do-i-calculate-the-offsets-for-pagination/27992616 # pylint: disable=unbalanced-tuple-unpacking page, per_page, offset = get_page_args( page_parameter='page', per_page_parameter='per_page', offset_parameter='offset') per_page = 12 offset = (page - 1) * per_page colls = mongo.db.categories.find() total = colls.count() colls_paginated = colls[offset: offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='materializecss') return render_template("all_collections.html", user=user, colls=colls_paginated, page=page, per_page=per_page, pagination=pagination) else: flash("You have to be an Admin to access this page") return render_template("403.html")
def account(username): username = mongo.db.users.find_one( # pylint: disable=unbalanced-tuple-unpacking {"username": session["user"]})["username"] # pylint: disable=unbalanced-tuple-unpacking page, per_page, offset = get_page_args( page_sparameter='page', per_page_parameter='per_page', offset_parameter='offset') per_page = 12 offset = (page - 1) * per_page user = mongo.db.users.find_one({"username": session["user"]}) recipes = list(mongo.db.recipes.find( {"created_by": ObjectId(user["_id"])})) total = len(recipes) recipes_paginated = recipes[offset: offset + per_page] pagination = Pagination( page=page, per_page=per_page, total=total, css_framework='materializecss') if session["user"]: for recipe in recipes: try: recipe["created_by"] = mongo.db.users.find_one( {"_id": recipe["created_by"]})["username"] except Exception: pass return render_template("account.html", username=username, recipes=recipes_paginated, page=page, per_page=per_page, pagination=pagination) return redirect(url_for("login"))
def list_ident_rules(): confirm_user_is_admin() # List all ident_dims with Sensitive field names sql = "select array_agg(f.sdf_name) as field_list, array_agg(f.sdf_id) as field_id_list, \ i.rule_id, i.risk_score, i.risk_type \ from mc_demo.identifiability_rules i \ left join mc_demo.sensitive_data_fields f \ on f.sdf_id = any(i.field_id_list) \ group by i.rule_id" result = db.engine.execute(sql) identlist = [row for row in result] # Sensitive data fields for populating the selectpicker sdflist = sdfdbo.query.order_by(asc(sdfdbo.sdf_name)).all() page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(identlist) pagination_idents = identlist[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('identifiability/identifiability_template.html', ident_dims=pagination_idents, sdf_dims=sdflist, pagination=pagination, page=page, per_page=per_page, title="Identifiability Rules")
def search(): """ Search function, takes the string used to search and returns all matches from the db. modified from CI walkthrough project. """ query = request.args.get("query") recipes = list(mongo.db.recipies.find({"$text": {"$search": query}})) page, per_page, offset = get_page_args( page_parameter='page', per_page_parameter='per_page', offset_parameter='offset') per_page = 3 offset = (page - 1) * 3 # My formula for getting the right offset recipe_paginated = recipes[offset: offset + per_page] total = mongo.db.recipies.find({"$text": {"$search": query}}).count() pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='materializecss') if len(recipes) == 0: flash(f"We're sorry but no recipes with {query} were found!") else: flash(f"Your search for {query} returned {len(recipes)} result(s)!") return render_template('recipes.html', recipes=recipe_paginated, page=page, per_page=per_page, pagination=pagination, )
def works(): """works: * Fetches every work uploaded to db. * Displays paginated works. \n Args: * None. \n Returns: * Template displaying all works in date_submitted descending order. """ works = list(mongo.db.works.find().sort("date_submitted", -1)) # pagination def get_works(offset=0, per_page=9): return works[offset: offset + per_page] page, per_page, offset = get_page_args( page_parameter='page', per_page_parameter='per_page' ) per_page = 9 total = len(works) pagination_works = get_works(offset=offset, per_page=per_page) pagination = Pagination( page=page, per_page=per_page, total=total, css_framework='bootstrap4' ) return render_template( "works.html", works=pagination_works, page=page, per_page=per_page, pagination=pagination )
def projects(): if request.args.get("recount") == "y": update_project_tallies() projects_ = db.projects.find() search = request.args.get("search") if not (search == None): projects = [] search = request.args.get("search") for proj in projects_: if str(search) in proj: projects.append(proj) else: projects = projects_ page, per_page, offset = get_page_args() from_ = 20 * (page - 1) to_ = 20 * page projects_render = projects[from_:to_] pagination = Pagination(page=page, offset=offset, per_page=20, total=projects.count(), search=False, record_name='projects') return render_template('project.html', projects=projects_render, pagination=pagination)
def producer_list(): """Show list of producers.""" # Query for all producers in database; return results alphabetized. producers = Producer.query.order_by("producer_name").all() page, per_page, offset = get_page_args(page_parameter="page", per_page_parameter="per_page") per_page = 100 offset = (page - 1) * per_page total = len(producers) pagination_producers = producers[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework="bootstrap4") return render_template("producer_list.html", producers=pagination_producers, page=page, per_page=per_page, pagination=pagination)
def index_pagination(job_name): """ This API is used to list the job based on their job name :param str job_name: Name of the Jenkins job :return: redirect the build history page """ fs = regex_data_retrieval(job_name=job_name) if fs.count() == 0: return render_template("404.html", title="404"), 404 try: pattern_type = re.search(r"\w*-\w*", job_name).group() except AttributeError: Common.logger.warn( f"index_pagination:failed to search the job name: {job_name}") pattern_type = job_name offset = {"page": 1, "per_page": Common.get_config_value("per_page")} page, per_page, offset = get_page_args(page_parameter="page", per_page_parameter="per_page", **offset) pagination_items = page_list(fs, per_page=per_page, offset=offset) pagination = Pagination(page=page, per_page=per_page, total=fs.count(), css_framework="bootstrap4") return render_template( "index_pagination.html", List=pagination_items, page=page, per_page=per_page, pagination=pagination, pattern_type=pattern_type, job_name=job_name, )
def profile(username): # gets session username from the database drinks = drinks_db.find({"created_by": username}) username = users_db.find_one({"username": session["user"]})["username"] # This will count the logged in users number of drinks number_drinks = drinks.count() page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') per_page = 8 offset = (page - 1) * per_page current_page = int(request.args.get('current_page', -1)) total = drinks_db.find().count() paginatedDrinks = drinks[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total) if session["user"]: return render_template("profile.html", username=username, drinks=paginatedDrinks, page=page, per_page=per_page, pagination=pagination, current_page=current_page, number_drinks=number_drinks) return redirect(url_for("login"))
def song_list(): """Show list of songs.""" # SQLALchemy query to return all song titles. songs = Song.query.order_by("song_title").all() page, per_page, offset = get_page_args(page_parameter="page", per_page_parameter="per_page") per_page = 100 offset = (page - 1) * per_page total = len(songs) pagination_songs = songs[offset:offset + per_page] pagination = Pagination(page=page, per_page=per_page, total=total, css_framework="bootstrap4") return render_template("song_list.html", songs=pagination_songs, page=page, per_page=per_page, pagination=pagination)
def list_(per_page, status='all'): "Lists the bookmarks." head_titles = [gettext("Bookmarks")] user_id = None filters = {} tag = request.args.get('tag', None) if tag: filters['tags_proxy__contains'] = tag query = request.args.get('query', None) if query: query_regex = '%' + query + '%' filters['__or__'] = {'title__ilike': query_regex, 'description__ilike': query_regex} if current_user.is_authenticated: # query for the bookmarks of the authenticated user user_id = current_user.id if status == 'public': # load public bookmarks only filters['shared'] = True elif status == 'private': # load private bookmarks only filters['shared'] = False else: # no filter: load shared and public bookmarks pass if status == 'unread': filters['to_read'] = True else: pass else: # query for the shared bookmarks (of all users) head_titles = [gettext("Recent bookmarks")] not_created_before = datetime.datetime.today() - \ datetime.timedelta(days=900) filters['time__gt'] = not_created_before # only "recent" bookmarks filters['shared'] = True bookmarks = BookmarkController(user_id) \ .read(**filters) \ .order_by(desc('time')) #tag_contr = BookmarkTagController(user_id) #tag_contr.read().join(bookmarks).all() page, per_page, offset = get_page_args() pagination = Pagination(page=page, total=bookmarks.count(), css_framework='bootstrap3', search=False, record_name='bookmarks', per_page=per_page) return render_template('bookmarks.html', head_titles=head_titles, bookmarks=bookmarks.offset(offset).limit(per_page), pagination=pagination, tag=tag, query=query)
def index(): g.cur.execute('select count(*) from users') total = g.cur.fetchone()[0] page, per_page, offset = get_page_args() sql = 'select name from users order by name limit {}, {}'\ .format(offset, per_page) g.cur.execute(sql) users = g.cur.fetchall() pagination = get_pagination(page=page, per_page=per_page, total=total, record_name='users', format_total=True, format_number=True, ) return render_template('index.html', users=users, page=page, per_page=per_page, pagination=pagination, )
def search(name): """The function is used to test multi values url.""" sql = 'select count(*) from users where name like ?' args = ('%{}%'.format(name), ) g.cur.execute(sql, args) total = g.cur.fetchone()[0] page, per_page, offset = get_page_args() sql = 'select * from users where name like ? limit {}, {}' g.cur.execute(sql.format(offset, per_page), args) users = g.cur.fetchall() pagination = get_pagination(page=page, per_page=per_page, total=total, record_name='users', ) return render_template('index.html', users=users, page=page, per_page=per_page, pagination=pagination, )
def orgs(): if request.args.get("recount") == "y": update_project_tallies() projects_ = db.projects.find() search = request.args.get("org") if not (search == None): projects = [] for proj in projects_: if str(search) in proj["project"].lower(): projects.append(proj) else: projects = projects_ page,per_page,offset = get_page_args() from_ = 20*(page-1) to_ = 20*page projects_render = projects[from_:to_] pagination = Pagination(page=page, offset=offset, per_page=20, total=len(projects), search=False, record_name='projects') return render_template('project.html',projects=projects_render, pagination=pagination)
def run_check(): check = request.args.get("check") matching_only = request.args.get("matching_only") ignore = "" ignore = request.args.get("ignore") ignore = str(ignore) filename = "" filemame = request.args.get("filename") filename = str(filename) results = [] txt_check = db.checks.find_one({"name":check}) regex = txt_check["check_regex"] check_name = str(txt_check["name"]) page,per_page,offset = get_page_args() per_page = 200 from_ = per_page*(page-1) if not (check_name in check_cache): reg = re.compile(regex) # uncomment when can figure out limit and offset with pymongo #findings = db.findings.find({"results":reg}) #total = 0 #for finding in findings: # if not ("Error pulling file" in finding["results"]): # total =+ 1 #check_cache[check_name] = total results = run_regex(regex,matching_only,from_,per_page) check_cache[check_name] = results results = results[from_:from_+per_page] else: results = check_cache[check_name][from_:from_+per_page] pagination = Pagination(page=page, offset=offset, per_page=per_page, total=len(check_cache[check_name]), search=False, record_name='results') return render_template('check_results.html', results=results, filename_=filename, ignore=ignore, pagination=pagination)
def user_stream(per_page, nickname=None): """ Display the stream of a user (list of articles of public feed). """ user_contr = UserController() user = user_contr.get(nickname=nickname) if not user.is_public_profile: if current_user.is_authenticated and current_user.id == user.id: flash(gettext('You must set your profile to public.'), 'info') return redirect(url_for('user.profile')) category_id = int(request.args.get('category_id', 0)) category = CategoryController().read(id=category_id).first() # Load the public feeds filters = {} filters['private'] = False if category_id: filters['category_id'] = category_id feeds = FeedController().read(**filters).all() # Re-initializes the filters to load the articles filters = {} filters['feed_id__in'] = [feed.id for feed in feeds] if category: filters['category_id'] = category_id articles = ArticleController(user.id).read_light(**filters) # Server-side pagination page, per_page, offset = get_page_args(per_page_parameter='per_page') pagination = Pagination(page=page, total=articles.count(), css_framework='bootstrap3', search=False, record_name='articles', per_page=per_page) return render_template('user_stream.html', user=user, articles=articles.offset(offset).limit(per_page), category=category, pagination=pagination)
def test_get_page_args_fails_outside_of_request_context(self): """get_page_args raises a RuntimeError if called with no request ctx. """ with pytest.raises(RuntimeError): get_page_args()