Untitled

 avatar
unknown
python
2 years ago
2.2 kB
5
Indexable
@app.route("/order", methods=("GET",))
def order_index():
    """Show all the orders."""
    error = None
    try:
        page = request.args.get("page", 1, type=int)
        items_per_page = 2 
        page_start_index = (page - 1) * items_per_page
        with pool.connection() as conn:
            with conn.cursor(row_factory=namedtuple_row) as cur:
                orders_page = cur.execute(
                    f"""
                    SELECT o.order_no, o.cust_no, STRING_AGG(c.sku, ',') AS sku_list
                    FROM orders o
                    JOIN contains c ON o.order_no=c.order_no
                    JOIN product p ON c.sku=p.sku
                    GROUP BY o.order_no 
                    ORDER BY o.order_no DESC
                    LIMIT {items_per_page}
                    OFFSET {page_start_index};
                    """,
                    {},
                ).fetchall()
               
                # fetchone(): retorna a primeira linha de resultados
                # como é um count() retorna um único valor que é o count.
                total_orders = cur.execute(
                    f"""
                    SELECT COUNT(DISTINCT o.order_no)
                    FROM orders o
                    JOIN contains c ON o.order_no=c.order_no
                    JOIN product p ON c.sku=p.sku;
                    """,
                    {},
                ).fetchone()[0]
                
        #log.debug(f"Found {cur.rowcount} rows.")
        # API-like response is returned to clients that request JSON explicitly (e.g., fetch)
        if (
            request.accept_mimetypes["application/json"]
            and not request.accept_mimetypes["text/html"]
        ):
            return jsonify(orders)
        
        # Se dividíssemos apenas total orders / items_per_page não consideraríamos
        # os possíveis iteis que não satisfazem uma página inteira e por isso fazem com que 
        # a divisão não seja inteira.
        total_pages = (total_orders + items_per_page - 1) // items_per_page
        return render_template("order/index.html", orders=orders_page, total_pages=total_pages, page = page)
    except Exception as e:
        return str(e)
Editor is loading...