使用 Flask 对 json 数据进行分页



我正在使用烧瓶并生成用我检索的JSON数据填充的表。我现在遇到的问题是我需要对所有 JSON 数据进行分页,因为每页的最大值设置为"50",我想在我的表格中显示所有产品。

到目前为止,我无法让它工作,我真的不知道如何让它与 Flask 一起工作。我尝试使用 while 循环,但这不适用于 Jinja2,因为无法识别该命令。

这是我的Python代码:

@app.route('/products',methods = ['POST', 'GET'])
def products():
shopnaam = request.form['shopname'] 
username = request.form['username']
password = request.form['password']
login = 'https://'+shopnaam+'example.com'
url = 'https://'+shopnaam+'.example.com/admin/products.json'
payload = {
'login[email]': username,
'login[password]': password
}
with requests.Session() as session:
post = session.post(login, data=payload)
r = session.get(url)
parsed = json.loads(r.text)

return render_template('producten.html',parsed = parsed)

这是我的Jinja2代码:

<button class="collapsible">Bekijk product Informatie</button>
<div class="content">
<table id = "productentabel">
<tr class = "header">
<th>ID</th>
<th>Titel </th>
<th>Prijs Exclusief BTW</th>
<th>Prijs Inclusief BTW</th>
<th>Datum</th>
{% for product in parsed['products'] %}
<TR>
<TD  width="100px" >{{product['id']}}</TD>
<TD  width="300px" >{{product['nl']['title']}}</TD>
<TD  width="150px">{{product['price_excl']}}</TD>
<TD  width="150px">{{product['price_incl']}}</TD>
<TD  width="300px">{{product['created_at']}}</TD>
</TR>
</tr>
{% endfor %}
</table>
<input class = "exportknop" value="Exporteer product informatie" type="button" onclick="$('#productentabel').table2CSV({header:['ID','Titel','Prijs Exclusief BTW', 'Prijs Inclusief BTW', 'Datum']})">     
</div>

如您所见,我正在使用 for 循环,此代码有效,但分页是问题所在。

我的 JSON 看起来像这样:

products: [
{
article_code: "123",
barcode: "456",
brand_id: 2600822,
created_at: "2018-05-31T15:15:34+02:00",
data01: "",
data02: "",
data03: "",
delivery_date_id: null,
has_custom_fields: false,
has_discounts: false,
has_matrix: false,
hits: 0,
hs_code: null,
id: 72660113,
image_id: null,
is_visible: false,
price_excl: 33.0165,
price_incl: 39.95,
price_old_excl: 0,
price_old_incl: 0,
product_set_id: null,
product_type_id: null,
search_context: "123 456 789",
shop_id: 252449,
sku: "789",
supplier_id: 555236,
updated_at: "2018-05-31T15:15:34+02:00",
variants_count: 1,
visibility: "hidden",
weight: 0,
links: {
first: ".json",
last: ".json?page=70",
prev: null,
next: ".json?page=2",
count: 3497,
limit: 50,
pages: 70
}

所以链接是分页发生的地方,我在我的 Python 代码中尝试了以下内容,这样我就可以在我的 python 终端中打印所有值。只有我不能将数据发送到表。

while url:
with requests.Session() as session:
post = session.post(login, data=payload)
r = session.get(url)
parsed = json.loads(r.text)
for product in parsed['products']:
print(product['id'], product['nl']['title'])
url = 'https://example/admin/products' + parsed['links']['next']  

所以这里有几件事需要考虑。 首先,使用生成器来创建Web内容在websocket或异步调用之外几乎是不可能的。 原因是WSGI在渲染之前需要所有数据。 然后它关闭连接。 您可以生成数据,但在表中,这将在原始 html 中引起问题。

怎么办:

我会使用类似数据表 (datatables.net( 的东西,将您的表数据馈送到变量中,并让数据表为您处理分页。

使用 Bootstrap 4 和数据表的示例。

<script>
var dataSet = []
var wurl = ""
tablex = $('#tablex').dataTable( {
select: true,
stateSave: true,
colReorder: true,
deferRender: true,
"oLanguage": {"sSearch": "Filter:"},
columns: [
{ title: "Number" },
{ title: "Client Name" },
{ title: "Opened" },
{ title: "Closed" },
{ title: "Worked" }
]
} );
function generate() {
$.get(wurl, function( data ) {
dataSet = data;
tablex.fnDestroy();
tablex = $('#tablex').dataTable( {
data: dataSet,
select: true,
stateSave: true,
colReorder: true,
deferRender: true,
"oLanguage": {"sSearch": "Filter:"},
columns: [
{ title: "Number" },
{ title: "Client Name" },
{ title: "Opened"},
{ title: "Closed"},
{ title: "Worked"}
],
} );
});
};
$(document).ready(function() {
wurl = '/api/getdata';
generate()
} );
</script>

我首先只建立一个基表,然后调用一个 API 并在后台加载该表的数据。 如果需要,您甚至可以进行此轮询并按间隔刷新数据集。 API 只是在列输出中提供原始数据。

在本例中,您的表 ID 为"tablex"。
API 路由可以是任何内容,只需以列和行格式的输出返回值。

最新更新