项目结构
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
books = [
{'title': 'Book 1', 'author': 'Author 1', 'year': 2020},
{'title': 'Book 2', 'author': 'Author 2', 'year': 2021},
{'title': 'Book 3', 'author': 'Author 3', 'year': 2022},
{'title': 'Book 4', 'author': 'Author 4', 'year': 2023},
{'title': 'Book 5', 'author': 'Author 5', 'year': 2024},
{'title': 'Book 6', 'author': 'Author 6', 'year': 2025},
{'title': 'Book 7', 'author': 'Author 7', 'year': 2026},
{'title': 'Book 8', 'author': 'Author 8', 'year': 2027},
{'title': 'Book 9', 'author': 'Author 9', 'year': 2028},
{'title': 'Book 10', 'author': 'Author 10', 'year': 2029},
{'title': 'Book 11', 'author': 'Author 11', 'year': 2030},
{'title': 'Book 12', 'author': 'Author 12', 'year': 2031},
# 添加更多图书信息...
]
@app.route('/home')
def index():
page = request.args.get('page', 1, type=int) # 获取页码参数,默认为1
per_page = 5 # 每页显示的图书数量
start_index = (page - 1) * per_page
end_index = start_index + per_page
books_subset = books[start_index:end_index] # 获取当前页的图书信息
return render_template('index.html', books=books_subset, page=page, total_pages=len(books) // per_page + 1, per_page=per_page)
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Books</title>
</head>
<body>
<h1>Books</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }} ({{ book.year }})</li>
{% endfor %}
</ul>
<div>
{% if page > 1 %}
<a href="?page={{ page - 1 }}">Previous</a>
{% endif %}
<span>Page {{ page }}</span>
{% if books|length >= per_page %}
<a href="?page={{ page + 1 }}">Next</a>
{% endif %}
</div>
</body>
</html>
示例图