Índice
processamento de dados de pandas
Inicialize a estrutura do Flask e configure o roteamento
Dados da lista de renderização do modelo Jinja
dados de solicitação de paginação
Mostrar exemplo de dados da página de detalhes
Exemplo de dados da página de lista
Exemplo de dados da página de detalhes
1. Cena de combate real
Como python usa pandas para exibir dados de arquivo csv em páginas em páginas da web flask
2. Pontos de conhecimento
sintaxe básica do python
Arquivo Python lido e gravado
paginação python
processamento de dados de pandas
estrutura da web do balão
modelo jinja
3. Combate real de novato
Inicialize a estrutura do Flask e configure o roteamento
'''
Description: 分页读取并显示 csv 文件数据
'''
from math import ceil
import csv
from flask import Flask, render_template, request, redirect
from spiders.file_manager import FileManager
# 初始化框架
web = Flask(__name__)
@web.route('/')
def index():
# 首页
return redirect('/table/1')
@web.route('/table/<int:page_num>')
def table(page_num):
# 分页读取并显示 csv 文件数据
file_manager = FileManager()
file = file_manager.get_data_file_path("tao365_detail.csv")
# 若不指定limits默认为 5
limits = request.args.get('limits', 5, type=int)
def show_csv(reader, page=page_num, limits=limits):
# 内部函数,根据limits和所在页数生成数据
df = []
for row in reader:
if page_num * limits >= (reader.line_num - 1) > (page_num - 1) * limits:
df.append(row)
return df
with open(file, 'r+', encoding='utf-8') as f:
# 计算页面数
row_length = len(f.readlines()) - 1
pages = int(ceil(row_length / limits))
with open(file, 'r+', encoding='utf-8') as f:
# 计算数据
reader = csv.reader(f)
next(reader)
df = show_csv(reader, page_num, limits)
# 加载模版和模版数据
return render_template('table.html', df=df, pages=pages, page_num=page_num, limits=limits)
@web.route('/table_detail')
def table_detail():
# 二手房详情
row = request.args.get('row').split(',')
return render_template('table_detail.html', row=row)
# 启动 flask web 框架
web.run(debug=True)
Dados da lista de renderização do modelo Jinja
<section id="team" class="header">
<div class="container">
<div class="section-title">
<h2> pandas 在网页中分页显示 csv 文件</h2>
<p>使用 Python、pandas、bootstrap、flask 框架等技术实现</p>
</div>
<!-- ======= 预览板块 ======= -->
<section class="counts section-bg">
<div class="container">
<div class="row">
<div class="col">
<!-- ======= 使用表格循环展示数据 ======= -->
<table class="table table-striped table-hover" style="">
<tbody>
<tr>
<th>标题</th>
<th>价格</th>
<th>每平方价格</th>
<!-- <th>小区</th> -->
<!-- <th>地址</th> -->
<th>房屋户型</th>
<th>建筑面积</th>
<th>所在楼层</th>
<th>房屋朝向</th>
<th>建筑年代</th>
<th>详情</th>
</tr>
{% for row in df %}
<!-- <li>{
{row}}</li> -->
<tr class="alt">
{% for subrow in row %} {% if loop.index != 5 and loop.index != 4 %}
<td>{
{subrow}}</td>
{% endif %} {% endfor %}
<td><a class="link-table" data-row="{
{row}}" href="/table_detail">点击查看</a> </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div id="demo" style="display: flex;justify-content: center;"></div>
</div>
</section>
<!-- End Counts Section -->
</div>
</section>
dados de solicitação de paginação
$(document).ready(function() {
$('.link-table').each(function() {
var row = $(this).attr('data-row')
var row1 = eval('(' + row + ')').join(',')
$(this).attr('href', '/table_detail?row=' + row1)
})
layui.use(['laypage', 'layer'], function() {
var laypage = layui.laypage,
layer = layui.layer;
laypage.render({
elem: 'demo',
count: "{
{pages}}",
curr: "{
{ page_num }}",
theme: '#587187',
// limit: pageSize //一页数据
jump: function(obj, first) {
console.log(obj.curr, first)
if (!first) {
window.location.href = "/table/" + obj.curr; //跳转链接
}
}
});
});
})
Mostrar exemplo de dados da página de detalhes
<section id="team" class="header">
<div class="container">
<div class="section-title">
<h2>pandas 在网页中分页显示 csv 文件 - 详情页数据示例</h2>
<p>使用 Python、pandas、bootstrap、flask 框架等技术实现</p>
</div>
<!-- ======= 预览板块 ======= -->
<section class="counts section-bg">
<div class="container">
<div class="detail__mainCotetnL fl">
<table class="table table-striped table-hover" style="">
<tbody>
<tr>
<td>标题</td>
<td colspan="3">{
{row[0]}}</td>
</tr>
<tr>
<td>价格</td>
<td>{
{row[1]}}</td>
<td>每平方价格</td>
<td>{
{row[2]}}</td>
</tr>
<tr>
<td>房屋户型</td>
<td>{
{row[5]}}</td>
<td>建筑面积</td>
<td>{
{row[6]}}</td>
</tr>
<tr>
<td>所在楼层</td>
<td>{
{row[7]}}</td>
<td>房屋朝向</td>
<td>{
{row[8]}}</td>
</tr>
<tr>
<td>建筑年代</td>
<td>{
{row[9]}}</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- End Counts Section -->
</div>
</section>
resultado da operação
executar captura de tela
* Servindo aplicativo Flask 'app_tao04'
* Modo de depuração: ativado
* Em execução em http://127.0.0.1:5000
Abra http://127.0.0.1:5000 no navegador
Exemplo de dados da página de lista
Exemplo de dados da página de detalhes
link de recurso
https://download.csdn.net/download/qq_39816613/87374650
Combate real novato, continue aprendendo!