Pagination in Flask using MySql

冷暖自知 提交于 2021-02-20 04:28:32

问题


I searched a lot about it. All the articles i get include SQLAlchemy and none of them deal with mysql. I am working with flask and i have a database in mysql and i need to display the data in pages. Like 1000 images, per page 10 so 100 pages. In mysql we can do pagination with the help of limit. And the routes can be:

@app.route('/images', defaults={'page':1})
@app.route('/images/page/<int:page>')

I need to ask is this all that is needed for pagination? or am i forgetting something important here? and mysql syntax would be:

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())

to get the first 20 results but how to get the next according to the pageno.? Flask-paginate library works only for tSQLAlchemy.


回答1:


Try this

@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())

May be this will help.




回答2:


Try this flask-mysql-paginate

You could then call the {{paginate.links}} in your html file




回答3:


Here it is, pure SQL solution.

SELECT * FROM table LIMIT [offset,] rows;
or
SELECT * FROM table LIMIT rows OFFSET offset;

For example:

select * from user
limit 100 offset 850100;


来源:https://stackoverflow.com/questions/24383223/pagination-in-flask-using-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!