database.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
config.py
import os from database import db from flask import Flask basedir=os.path.abspath(os.path.dirname(__name__)) app = Flask(__name__) #Dabase configuration app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI') or 'sqlite:///'+ os.path.join(basedir,'app.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app)
models.py
from database import db from config import app class StudentMore(db.Model): __tablename__= 'Students' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(108), nullable=False) score = db.Column(db.Integer, nullable=False) def __repr__(self): return 'StudentMore %r' % self.name with app.app_context(): db.create_all()
app.py
from flask import Flask,render_template from flask import redirect from flask import url_for from database import db from config import app from models import StudentMore @app.route('/stu/query/<int:page>', methods=['GET']) def query_stu(page=None): if not page: page = 1 students = StudentMore.query.paginate(page=page,per_page=5) # page是第幾頁,per_page是將每5個一頁 db.session.commit() # students.items是分頁展示的資料 return render_template("student.html", studentList=students.items, pagination=students) @app.route('/') def index(): return redirect(url_for("query_stu",page=1)) if __name__=="__main__": app.run(debug=True)
templates/page.html
<!--這個是分頁展示下面的頁碼--> {%macro my_paginate(pagination,url)%} <nav> <ul class="pagination"> {%if pagination.has_prev%} <li class="page-item active"><a class="page-link" href="{{url_for(url,page=pagination.page-1)}}">上一頁</a></li> {%else%} <li class="page-item disabled"><a class="page-link" href="#">上一頁</a></li> {%endif%} {%for page in pagination.iter_pages()%} {%if page%} <li class="page-item {%if page==pagination.page%}active{%endif%}"><a class="page-link" href="{{url_for(url,page=page)}}">{{page}}</a></li> {%else%} <li class="page-item disabled"><a class="page-link" href="#">…</a></li> {%endif%} {%endfor%} {%if pagination.has_next%} <li class="page-item active"><a class="page-link" href="{{url_for(url,page=pagination.page+1)}}">下一頁</a></li> {%else%} <li class="page-item disabled"><a class="page-link" href="#">下一頁</a></li> {%endif%} </ul> </nav> {%endmacro%}
student.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>學生</title> <style> ul { margin: auto; width: 241px; } ul li { float: left; margin-right: 16px; list-style: none; } ul li a { text-decoration: none; } ul li a:hover { color: orange; } .active a{ color: red ; } .disabled a { color: gray ; } </style> </head> <body> <div align="center"> <h2>使用者資訊</h2> <br><br> {% for stu in studentList %} 編號:{{ stu['id'] }},姓名:{{ stu['name'] }},成績:{{ stu['score'] }} <br><br> {% endfor %} </div> <!-- 匯入下面的頁碼--> {%import 'page.html' as pg%} {{pg.my_paginate(pagination,'query_stu')}} <!--query_stu是對應的方法名稱是什麼,然後在點選頁碼時可以找到該方法,從而展示資料--> </body> </html>