我目前正在尝试在python中构建一个小的flask应用程序,该应用程序通过熊猫接收一个csv并分页结果。我已经完成了使用pandas导入数据集,将其转换为字典列表以及使用flask_paginate将结果分页到表的过程。
现在,我想扩展此代码,以允许查询数据集中的术语(例如,在“客户名称”包含“巴里”的所有结果中显示并分页)。我知道我需要使用输入框并处理发布请求,但我不确定如何在索引路由中将它们连接在一起。
任何帮助将不胜感激。
app.py的代码
from flask import Flask, render_template
from flask_paginate import Pagination, get_page_args
import pandas
app = Flask(__name__)
app.debug = True
df = pandas.read_csv('static/superstore.csv')
data = df.to_dict(orient = 'records')
def get_users(offset=0, per_page=20):
return data[offset: offset + per_page]
@app.route('/')
def index():
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
total = len(data)
pagination_users = get_users(offset=offset, per_page=per_page)
pagination = Pagination(page=page,
per_page=per_page,
total=total,
css_framework='bootstrap4')
return render_template('index.html',
data=pagination_users,
page=page,
per_page=per_page,
pagination=pagination)
index.html的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>flask-bootstrap example</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/main.css">
</head>
<body>
<div class = "bg-primary">
<div class = "container jumbotron jumbotron-fluid bg-transparent text-white">
<h1 class = "display-4">Pagination Example</h1>
</div>
</div>
<div class="container">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Profit</th>
<th>Unit Price</th>
<th>Order Quantity</th>
<th>Customer Name</th>
<th>Region</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item['Order ID'] }}</td>
<td>{{ item['Order Date'] }}</td>
{%if item['Profit'] > 0%}
<td><span class ="badge badge-success">{{ item['Profit'] }}</span></td>
{%else%}
<td><span class ="badge badge-danger">{{ item['Profit'] }}</span></td>
{%endif%}
<td>{{ item['Unit Price'] }}</td>
<td>{{ item['Order Quantity'] }}</td>
<td>{{ item['Customer Name'] }}</td>
<td>{{ item['Region'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{{ pagination.links }}
</div>
</body>
</html>