暑期实训记录:第三周(3)

flask分页功能的实现

经过前几天的学习和铺垫,我掌握了关于flask数据库管理,ORM,模型,类,Query对象等知识,为分页功能的实现打下了基础,并完成了flask分页功能的实现。现将过程记录如下:
1.引入需要的package


from flask_sqlalchemy import SQLAlchemy

2.数据库配置,并创建数据库应用实例


# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://postgres:000@localhost:5432/cuisine"

# 指定当视图执行完毕后,自动提交数据库操作
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# 指定每次执行操作时打印原始的SQL语句
app.config['SQLALCHEMY_ECHO'] = True

# 【手动增加配置选项】关于使用SQLALCHEMY 出现warning 的问题解决
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True

# 创建数据库应用实例
db = SQLAlchemy(app)

3.根据数据库的关系表,创建对应的实体类


# 创建实体类
class Cuisine(db.Model):
    # 定义表名
    __tablename__ = 'cuisine'
    #定义列
    c_name = db.Column(db.Text, primary_key=True)
    picture = db.Column(db.Text)
    ingredients = db.Column(db.Text)

    def __init__(self, c_name, picture, ingredients):
        self.c_name = c_name
        self.picture = picture
        self.ingredients = ingredients

    def __repr__(self):
        return '<{},{},{}>'.format(self.c_name, self.picture, self.ingredients)

4.引用paginate类,完成分页功能


@app.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    per_page = int(request.args.get('per_page', 8))
    paginate = Cuisine.query.paginate(page, per_page, error_out=False)
    # paginate = Cuisine.query.order_by(Cuisine.c_name.desc()).paginate(page, per_page, error_out=False)
    cuisine = paginate.items
    return render_template('firstproj.html', meal_data=cuisine, pagination=paginate)

5.将得到的参数传入html,并通过调用宏实现分页功能


{% import "_macros.html" as macros %}
......
    <div class="page">
        {%if pagination%}
            <div class="pagination">
                {{ macros.pagination_widget(pagination, '.index') }}
            </div>
        {% endif %}
    </div>

finished.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值