在Flask中使用MySql进行分页
我查了很多资料,发现所有的文章都提到SQLAlchemy,但没有一篇是关于mysql的。我正在使用flask,并且我的数据库是mysql,我需要把数据分成几页来显示。比如说有1000张图片,每页显示10张,这样就需要100页。
在mysql中,我们可以通过使用限制(limit)来实现分页。路由可以是:
@app.route('/images', defaults={'page':1})
@app.route('/images/page/<int:page>')
我想问的是,这样做分页就够了吗?还是我漏掉了什么重要的东西?mysql的语法是:
db = mysql.connect('localhost', 'root', 'password', 'img')
cursor = db.cursor()
cursor.execute('SELECT Id,Title,Img FROM image ORDER BY RAND() limit 20 offset 0;')
data = list(cursor.fetchall())
这样可以获取前20个结果,但如果想根据页码获取下一页的内容该怎么做呢?Flask-paginate这个库只适用于tSQLAlchemy。
3 个回答
1
这里有一个纯粹的SQL解决方案。
SELECT * FROM table LIMIT [offset,] rows;
or
SELECT * FROM table LIMIT rows OFFSET offset;
比如说:
select * from user
limit 100 offset 850100;
2
试试这个 flask-mysql-paginate
然后你可以在你的html文件中使用{{paginate.links}}来调用它
5
试试这个
@app.route('/images', defaults={'page':1})
@app.route('/images/page/<int:page>')
def abc(page):
perpage=20
startat=page*perpage
db = mysql.connect('localhost', 'root', 'password', 'img')
cursor = db.cursor()
cursor.execute('SELECT Id,Title,Img FROM image limit %s, %s;', (startat,perpage))
data = list(cursor.fetchall())
也许这个会对你有帮助。