اذهب إلى المحتوى
  • 0

كيفية عمل pagination في فلاسك Flask؟

Mohssen A Mohssen

السؤال

أحاول أن أقوم بعرض بعض المنشورات في شكل صفحات pagination ، لكن لا أعرف من أين أبدأ أو كيف أقوم بعمل هذا الأمر

في البداية بدأت أقوم بجلب كل المنشورات من قاعدة البيانات بإستخدام Flask-SQLAlchemy، ثم أقوم بتقسيمها إلى صفحات أم ماذا؟

أشعر بالتشتت في هذه الجزئية، ما هو المطلوب بالتحديد لكي أقوم بعمل pagination في فلاسك Flask؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1

هذا مثال بسيط لفهم تقسيم الصفحات الخاص ب Flask-SQLAlchemy.

  • نفرض أنه يوجد لدينا صفحة نقوم بعرض مجموعة من الألوان بداخلها.
    • أولاُ نقوم بجلب الألوان:
      @app.route('/colors')
      def colors():
          # نجلب الألوان من قاعدة البيانات
          # ونعرضها في القالب
          colors = Color.query.all()
          return render_template('colors/all_colors.html', colors=colors)

       

    • ثانيا نعرض الألوان في القالب:

      <div class="table-responsive">
          <table class="table table-sm table-borderless mb-0">
              <thead class="thead-dark">
                  <tr>
                      <th>S/N</th>
                      <th>Color Name</th>
                      <th>Date Created</th>
                      <th>Actions</th>
                  </tr>
              </thead>
              <tbody>
                  {% for color in colors %}
                  <tr>
                      <th scope="row">{{ loop.index }}</th>
                      <td>{{ color.name }}</td>
                      <td>{{ color.created_at }}</td>
                  </tr>
                  {% endfor %}
              </tbody>
          </table>
      </div>

      كل الألوان سيتم عرضُها.  حتى ولو كان عددها كبيراً جداً وهذا سيؤدي إلى ثقل في تحميل الصفحة.

    • الحل طبعا هو إضافة ال pagination. لإضافتها نغير الشفرة إلى:

      ROWS_PER_PAGE = 10 # نعين عدد الالوان التي نريدها في كل صفحة
      @app.route('/colors')
      def colors():
          # نضغ إعدادات الترقيم
          page = request.args.get('page', 1, type=int)
          #  نستعمل الدالة paginate 
          # من   Flask SQLAlchemy
          # ونمرر لها الصفحة الحالية مع عدد الألوان في كل صفحة
          colors = Color.query.paginate(page=page, per_page=ROWS_PER_PAGE)
          return render_template('colors/all_colors.html', colors=colors)

       

    • نقوم بتعديل القالب: لعرض العناصر يجب إستدعاء colors.items  بدل colors.

      <div class="table-responsive">
          <table class="table table-sm table-borderless mb-0">
              <thead class="thead-dark">
                  <tr>
                      <th>S/N</th>
                      <th>Color Name</th>
                      <th>Date Created</th>
                      <th>Actions</th>
                  </tr>
              </thead>
              <tbody>
                  {% for color in colors.items %}
                                  ^^^^^^^^^^^^
                  <tr>
                      <th scope="row">{{ loop.index }}</th>
                      <td>{{ color.name }}</td>
                      <td>{{ color.created_at }}</td>
                  </tr>
                  {% endfor %}
              </tbody>
          </table>
      </div>
      <!-- إنشاء روابط تقسيم الصفحات -->
      <div class="text-right">
          <a href="{{ url_for('colors', page=colors.prev_num) }}"
             class="btn btn-outline-dark 
             {% if colors.page == 1 %}disabled{% endif %}">
              &laquo;
          </a>
      	<!-- نعمل حلقة لعمل رابط لكل صفحة -->
          {% for page_num in colors.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
      	{% if page_num %}
      		<!-- نقوم بكتابة شرط للتحقق من الصفحة الحالية-->
                  {% if colors.page == page_num %}
                  <a href="{{ url_for('colors', page=page_num) }}"
                     class="btn btn-dark">
                      {{ page_num }}
                  </a>
                  {% else %}
                  <a href="{{ url_for('colors', page=page_num) }}"
                     class="btn btn-outline-dark">
                      {{ page_num }}
                  </a>
                  {% endif %}
              {% else %}
                  ...
              {% endif %}
          {% endfor %}
          <a href="{{ url_for('colors', page=colors.next_num) }}"
             class="btn btn-outline-dark 
             {% if colors.page == colors.pages %}disabled{% endif %}">
              &raquo;
          </a>
      </div>
      <p class="text-right mt-3">
         Showing page {{ colors.page }} of {{ colors.pages }}
      </p>

       

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1

هدفنا هو استخدام عنوان URL مثل هذا

/v1/magazines?page=1&per-page=50

لإنشاء نتائج JSON مثل هذا:

{
    "results": [
        {
            "Programming Today",
            "publisher": "Harper Collins"
        },
        {
            "title": "Mountain Biking",
            "publisher": "Outdoors Limited"
        }
    ],
    "pagination": {
        "count": 2,
        "page": 1,
        "per_page": 50,
        "pages": 1
    }
}
@app.route("/magazines")
def magazines():
    # process query parameters
    page = request.args.get("page", 1, type=int)
    per_page = request.args.get("per-page", 100, type=int)

    # query
    magazines = Magazine.query.paginate(page, per_page)

    # combine results with pagination
    results = {
        "results": [{"title": m.title, "publisher": m.publisher} for m in magazines.items],
        "pagination": {
            "count": magazines.total,
            "page": page,
            "per_page": per_page,
            "pages": magazines.pages,
        },
    }
    return jsonify(results)

هذا هو! تمنحنا طريقة ترقيم الصفحات في استعلام sqlalchemy الكثير من المرونة مع القليل جدًا من التعليمات البرمجية  وإرجاع مجموعة نتائج محدودة  وعرض إجمالي السجلات المتاحة  أثناء حساب الصفحات المتبقية بناءً على إعدادنا لكل صفحة.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...