Python/Flask

[Flask] Pagination 구현

yubi5050 2022. 5. 29. 20:42

DB 에서 값을 가져와 Ranking을 출력 해본다. 

GET 방식으로 URL에 page_num=1을 붙여서 보내주는 것이 핵심.

ranking.html

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
    <section>
        <div class="ranking_box">
            {% set page_count = (ranking_list|length)//page_unit %} <!-- page 수 -->
            {% set start = page_count*(page_num-1) %}               <!-- 글 시작 번호 -->
            {% set result_list = ranking_list[start : start+4] %}   <!-- 출력할 글 -->
            <table>
                <tr><th>name</th><th>score</th><th>date</th></tr>
                <!-- 글 출력 -->
                {% for result in result_list %}
                    <tr><td>{{result['name']}}</td><td>{{result['score']}}</td><td>{{result['date']}}</td></tr>
                {% endfor %}
            </table>
            <!-- 글 페이지 번호 -->
            {% for i in range(1, (page_count)+2)%}
                <a href="/?page_num={{ i }}">{{i}}</a>
            {% endfor %}
        </div>
    </section>
</body>
</html>

 

app.py

# Flask
from flask import Flask, request, render_template

# DB 연결 코드
from pymongo import MongoClient

client = MongoClient('<your mongo db path>')
db = client.pagination

app = Flask(__name__)

# page 당 출력 글 수
PAGE_UNIT = 4

@app.route('/', methods=['GET'])
def ranking():
    if request.method == 'GET':
        # DB 조회
        result_info = list(db.RESULT.find({"company" : "(주)럭키세븐"}, {'_id': False}))
        ranking_list = [{'name':result['name'], 'score': result['score'], 'date': result['date']} for result in result_info]
        ranking_list = sorted(ranking_list, key=lambda x: x['date']) # Date 별 정렬
        
        # page 관련
        page_num = request.args.get('page_num',default=1, type=int)
        # print('== 현재 페이지 번호는' , page_num)
        return render_template('/ranking.html', ranking_list=ranking_list, page_unit=PAGE_UNIT, page_num=page_num)

    else: # POST
        return render_template('/ranking.html')

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

 

결과 화면