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.