广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Flask 系列之 Pagination
  • 277
分享到

Flask 系列之 Pagination

系列之FlaskPagination 2023-01-31 00:01:40 277人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

说明 操作系统:windows 10 python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 实现当前登录用户的事务浏览、添加、删除 操作 实现 首先,在我们的 todolist\f

说明

实验目标

实现当前登录用户的事务浏览、添加、删除 操作

实现

首先,在我们的 todolist\fORMs.py 中添加事务添加对应的表单类 ThingForm,示例代码如下所示:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, PassWordField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from models import User


class ReGISterForm(FlaskForm):
    username = StringField('用户名:', validators=[
                           DataRequired(), Length(min=6, max=20)])
    email = StringField('邮箱:', validators=[DataRequired(), Email()])
    pwd = PasswordField('密码:', validators=[
        DataRequired(), Length(min=8, max=120)])
    confirm = PasswordField('确认密码:', validators=[
                            DataRequired(), EqualTo('pwd')])
    submit = SubmitField('提交')

    def validate_username(self, username):
        user = User.query.filter_by(name=username.data).first()
        if user:
            raise ValidationError("用户昵称已存在。")

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user:
            raise ValidationError('邮箱已存在.')


class LoginForm(FlaskForm):
    username = StringField('用户名:', validators=[
                           DataRequired(), Length(min=6, max=20)])
    password = PasswordField('密码:', validators=[DataRequired()])
    submit = SubmitField('登陆')

    def validate_username(self, username):
        user = User.query.filter_by(name=username.data)
        if not user:
            raise ValidationError('用户名不存在。')


class ThingForm(FlaskForm):
    title = StringField('标题:', validators=[
                        DataRequired(), Length(min=6, max=20)])
    text = TextAreaField('内容:', validators=[DataRequired()])
    submit = SubmitField('提交')

接着修改 todolist\app\views.py ,添加当前用户事务的添加、删除,示例代码如下所示:

from flask import render_template, redirect, url_for, flash, request
from flask_login import login_user, login_required, current_user, loGout_user
from app import app, db
from forms import ThingForm, RegisterForm, LoginForm
from models import User, Thing


@app.context_processor
def inject_user():
    user = User.query.first()
    return dict(user=user)


@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ThingForm()
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    if request.method == 'POST' and form.validate_on_submit():
        user_id = current_user.id
        title = form.title.data
        text = form.text.data
        thing = Thing(user_id=user_id, title=title, text=text)
        db.session.add(thing)
        db.session.commit()
        flash('添加成功')
    page = request.args.get('page', 1, type=int)
    things = current_user.things.order_by(
        Thing.add_date.desc()).paginate(page, 2, False)
    print(things)
    return render_template('index.html', title="首页", form=form, things=things)


@app.route('/login', methods=['POST', 'GET'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        name = form.username.data
        pwd = form.password.data
        user = User.query.filter_by(name=name).first()
        if user and user.check_password_hash(pwd):
            login_user(user)
            flash('登陆成功。', category='info')
            return redirect(url_for('index'))
        else:
            flash("密码或账户错误。", category='error')
    return render_template('login.html', title='登录', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('再见!')
    return redirect(url_for('login'))


@app.route('/register', methods=['POST', 'GET'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        pwd = form.pwd.data
        user = User(name=username, email=email)
        user.generate_password_hash(pwd)
        db.session.add(user)
        db.session.commit()
        flash('注册成功', category='info')
        return redirect(url_for('login'))
    return render_template('register.html', title='注册', form=form)


@app.route('/delete/<int:id>')
@login_required
def delete(id):
    thing = Thing.query.get(id)
    if thing:
        db.session.delete(thing)
        db.session.commit()
        return redirect(url_for('index'))

最后,完善 todolist\app\templates\index.html,添加数据展示相关代码,示例代码如下所示:

{% extends 'base.html' %} {% block content %} {% if current_user.is_authenticated and user %}
<h1 class="m-4">{{ current_user.name }},欢迎回来</h1>
{% endif %}

<div class="container-fluid">
    <p>
        <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
            添加新事务
        </a>
    </p>
    <div class="collapse" id="collapseExample">
        <div class="card card-body mb-4">
            {% from 'bootstrap/form.html' import render_form %} {{ render_form(form) }}
        </div>
    </div>

    <ul class="list-group">
        {% for thing in things.items %}
        <li class="list-group-item">
            <h4 style="display:block;float:left;padding-top:2px">
                {{ thing.title }}
            </h4>
            <div style="display:block;float: right;">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter{{thing.id}}">查看</button>
                <a class="btn btn-danger" href='/delete/{{ thing.id }}'>删除</a>
            </div>
        </li>

        <div class="modal fade" id="exampleModalCenter{{thing.id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">{{ thing.title }}</h5>
                    </div>
                    <div class="modal-body">
                        {{ thing.text }}
                    </div>
                    <div class="modal-footer">
                        <small>{{ thing.add_date }}</small>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </ul>

    <nav aria-label="Page navigation example" class="m-4">
        <ul class="pagination justify-content-center">
            <li class="page-item {% if not things.has_prev %}disabled{% endif %}">
                <a class="page-link" href="{{ url_for('index',page=things.prev_num) }}">上一页</a>
            </li>

            {% for page in things.iter_pages(1,1,3,2) %} {% if page %}
            <li class="page-item {%if page==things.page%}active{%endif%}">
                <a class="page-link" href="{{ url_for('index',page=page) }}">{{page}}</a>
            </li>
            {% else %}
            <li class="page-item disabled">
                <a class="page-link" href="#">&hellip;</a>
            </li>
            {% endif %} {% endfor %}

            <li class="page-item {% if not things.has_next %}disabled{% endif %}">
                <a class="page-link" href="{{ url_for('index',page=things.next_num) }}">下一页</a>
            </li>
        </ul>
    </nav>

</div>

{% endblock %}

此时,当我们运行起我们的网站后进入注册页面 Http://127.0.0.1:5000 就可以进行当前登录用户的事务录入、查看、删除、和事务分页的效果了。

补充

一个 Pagination 对象的常用属性有:

  • items 当前页面中的所有记录(比如当前页上有5条记录,items就是以列表形式组织这5个记录)
  • query 当前页的query对象(通过query对象调用paginate方法获得的Pagination对象)
  • page 当前页码(比如当前页是第5页,返回5)
  • prev_num 上一页页码
  • next_num 下一页页码
  • has_next 是否有下一页 True/False
  • has_prev 是否有上一页 True/False
  • pages 查询得到的总页数 per_page 每页显示的记录条数
  • total 总的记录条数

常用方法有:

  • prev() 上一页的分页对象Pagination
  • next() 下一页的分页对象Pagination
  • iter_pages(left_edge=2,left_current=2,right_current=5,right_edge=2)
  • iter_pages 用来获得针对当前页的应显示的分页页码列表。
  • 假设当前共有100页,当前页为50页,按照默认的参数设置调用iter_pages获得的列表为:[1,2,None,48,49,50,51,52,53,54,55,None,99,100]

--结束END--

本文标题: Flask 系列之 Pagination

本文链接: https://www.lsjlt.com/news/181702.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Flask 系列之 Pagination
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 实现当前登录用户的事务浏览、添加、删除 操作 实现 首先,在我们的 todolist\f...
    99+
    2023-01-31
    系列之 Flask Pagination
  • Flask 系列之 LoginManag
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask-login 进行会话管理的相关操作,并完成用户合法性登陆和退出。 ...
    99+
    2023-01-31
    系列之 Flask LoginManag
  • Flask 系列之 SQLAlchemy
    SQLAlchemy 是一种 ORM 框架,通过使用它,可以大大简化我们对数据库的操作,不用再写各种复杂的 sql语句 了。 说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv...
    99+
    2023-01-31
    系列之 Flask SQLAlchemy
  • Flask 系列之 FlaskForm
    通过使用 FlaskForm ,可以方便快捷的实现表单处理。 说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask_...
    99+
    2023-01-31
    系列之 Flask FlaskForm
  • Flask 系列之 Bootstrap-
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 Bootstrap-Flask 来进行页面美化,为网站应用上 Bootstra...
    99+
    2023-01-31
    系列之 Flask Bootstrap
  • Flask 系列之 Migration
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask-migrate 实现数据库的迁移操作 实验 安装环境包 pip i...
    99+
    2023-01-31
    系列之 Flask Migration
  • Flask 系列之 Blueprint
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 学习如何使用 Blueprint 介绍 接触过 DotNet MVC 开发的朋友应该都对...
    99+
    2023-01-31
    系列之 Flask Blueprint
  • Flask 扩展系列之 Flask-R
    简介 安装 快速入门 一个最小的 api 例子 资源丰富的路由 端点 参数解析 数据格式化 完整 TODO 应用例子 Flask-RESTful是一个Flask的扩展,它增加了对快速构建REST APIs的支持。它是一种轻...
    99+
    2023-01-31
    系列之 Flask
  • Flask 系列之 构建 Swagger
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验 环境初始化 # 创建项目目录 mkdir helloworld cd helloworld ...
    99+
    2023-01-31
    系列之 Flask Swagger
  • Flask 系列之 优化项目结构
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 完善环境配置,添加 异常请求 处理 实现 400、404 和 500 处理 首先,在 t...
    99+
    2023-01-31
    结构 项目 系列之
  • Flask入门系列Cookie与session的介绍
    目录一、Cookie的使用1、什么是Cookie2、在Flask中使用Cookie二、session的使用1、什么是session2、Flask中的session对象3、在Flask...
    99+
    2022-11-12
  • redis系列之-
    什么是主从复制 Redis的主从复制机制是指可以让从服务器(slave)能精确复制主服务器(master)的数据,如下图所示:             或者              主从复制的方式和工作原理 工作方式: Redis主从复制...
    99+
    2017-12-10
    redis系列之-
  • ES6系列之Generator
    一、什么是Generator 函数1.1 语法学习 Generator 语法,你需要了解function* 、yield、next三个基本概念。function* 用来声明一个函数是生成器函数,它比普通的函数声明多了一个*,*的位置比较随意...
    99+
    2023-06-03
  • Java系列之Predicate
    Java8引入了许多函数式接口(Functional Interface),Predicate(断言)就是其中一个,它的主要作用可以简单描述为:向其传入一个对象(可以理解为参数),将得到一个布尔值作为...
    99+
    2023-09-01
    java Java8 Optional 断言 函数式编程
  • Openssl之PEM系列
    Openssl之PEM系列1.PEM编码文件结构介绍PEM全称是Privacy Enhanced Mail,该标准定义了加密一个准备要发送邮件的标准,主要用来将各种对象保存成PEM格式,并将PEM格式的各种对象读取到相应的结构中。它的基本流...
    99+
    2023-06-04
  • OpenStack Juno系列之L3
    OpenStack L3 HA agent and VRRPactive/active此方案描述利用了模块化layer 2 (ML2) 插件与Open vSwitch (OVS) OpenStack对 Networking Layer 3 ...
    99+
    2023-01-31
    系列之 OpenStack Juno
  • 2Python全栈之路系列之SQLAchemy
    Python全栈之路系列之SQLAlchemySQLAlchemy的是Python SQL工具包和对象关系映射器,让应用程序开发者的全部功能和SQL的灵活性。它提供了一套完整的众所周知的企业级持久性模式,专...
    99+
    2022-10-18
  • Python全栈之路系列之Python
    The Python interpreter has a number of functions and types built into it that are always available. They are listed her...
    99+
    2023-01-31
    之路 系列之 Python
  • 3Python全栈之路系列之D
    模板是一个文本,用于分离文档的表现形式和内容,模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。如何使用模板系统在Python代码中使...
    99+
    2023-01-31
    之路 系列之 Python
  • 3Python全栈之路系列之Rabbit
    RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件。RabbitMQ服务器是用Erlang语言编写的,它可以为你的应用提供一个通用的消息发送和接收平台,并且保证消息在传输过程中的安全,RabbitMQ官网,RabbitM...
    99+
    2023-01-31
    之路 系列之 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作