Python flask 实现分页显示MySQL数据前端和后端代码
时间: 2024-05-11 07:15:22 浏览: 108
下面是一个简单的 Python Flask 分页实现,供您参考:
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>分页显示MySQL数据</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{% for data in result %}
<tr>
<td>{{ data.id }}</td>
<td>{{ data.name }}</td>
<td>{{ data.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
{% if prev %}
<a href="?page={{ prev }}">previous</a>
{% endif %}
{% if next %}
<a href="?page={{ next }}">next</a>
{% endif %}
</body>
</html>
```
后端代码:
```python
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'
db = SQLAlchemy(app)
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
age = db.Column(db.Integer)
@app.route('/')
def index():
page = request.args.get('page', 1, type=int)
per_page = 10
result = Users.query.order_by(Users.id.desc()).paginate(page, per_page, error_out=False)
prev = None
if result.has_prev:
prev = result.prev_num
next = None
if result.has_next:
next = result.next_num
return render_template('index.html', result=result.items, prev=prev, next=next)
if __name__ == '__main__':
app.run(debug=True)
```
希望能对您有所帮助!
阅读全文