利用tornado实现表格文件预览

26次阅读

共计 6035 个字符,预计需要花费 16 分钟才能阅读完成。

项目介绍
  本文将介绍笔者的一个项目,主要是利用 tornado 实现表格文件的预览,能够浏览的表格文件支持 CSV 以及 Excel 文件。预览的界面如下:

  下面我们将看到这个功能是如何通过 tornado 来实现的。
代码
  该项目的代码结构如下图所示:

  其中主要分为四个部分:

files
static
templates
py 代码

其中,files 文件夹为上传的表格文件的存放路径,static 为前端的静态文件,后续将不用给出介绍,读者可以从该项目的 github 中下载(下载地址详见后面),templates 文件夹主要存放 HTML 文件,而 py 文件用于后端控制。
  首先让我们看三个 HTML 文件,先是 upload.html,其代码如下:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title> 文件上传 </title>
<link rel=”shortcut icon” href=”{{static_url(‘images/flower.ico’)}}”>
<link rel=”stylesheet” href=”{{static_url(‘CSS/amazeui.min.css’)}}”>
<script src=”{{static_url(‘JS/amazeui.min.js’)}}”></script>
<script>
$(function() {
$(‘#doc-form-file’).on(‘change’, function() {
var fileNames = ”;
$.each(this.files, function() {
fileNames += ‘<span class=”am-badge”>’ + this.name + ‘</span> ‘;
});
$(‘#file-list’).html(fileNames);
});
});
</script>
</head>
<body>

<div align=”center”>
<br><br>
<h1> 表格文件上传 </h1>
<form action=’file’ enctype=”multipart/form-data” method=’post’>
<div class=”am-form-group am-form-file”>
<button type=”button” class=”am-btn am-btn-primary am-btn-sm”> 选择要上传的文件 </button>
<input id=”doc-form-file” type=”file” name=”file” multiple>
</div>
<div id=”file-list”></div>
<p>
<button type=”submit” class=”am-btn am-btn-default”> 提交 </button>
</p>
</form>
<p><a href=”/file_review”><button class=”am-btn am-btn-danger”> 查看全部文件 </button></a></p>

</div>

</body>
</html>
这个是文件上传的网页,界面如下:

选择上传文件,完成上传后,则会显示如下界面:

接着是 fileReview.html,其代码如下:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title> 文件浏览 </title>
<link rel=”shortcut icon” href=”{{static_url(‘images/flower.ico’)}}”>
<link rel=”stylesheet” href=”{{static_url(‘CSS/bootstrap.min.css’)}}”>
<link rel=”stylesheet” href=”{{static_url(‘CSS/amazeui.min.css’)}}”>
</head>
<body>

<div align=”center”>
<br><br>
<h1> 文件浏览 </h1>
<ul class=”list-group” style=”width:800px;text-align:left”>
{% for file in files %}
{% if file.endswith(‘.csv’) or file.endswith(‘.xls’) or file.endswith(‘.xlsx’) %}
<li class=”list-group-item”> <a href={{“/data?file=”+file}}>{{file}}</a></li>
{% end %}
{% end %}
</ul>
<a href=”/file”><button class=”btn btn-success” id=”review”> 文件上传界面 </button></a>
</div>

</body>
</html>
该页面主要用于显示上传的表格文件,界面如下:

最后是 dataReview.html,代码如下:
<!DOCTYPE html>
<html>

<head>
<meta charset=”UTF-8″>
<title> 数据预览 </title>
<link rel=”shortcut icon” href=”{{static_url(‘images/flower.ico’)}}”>
<link rel=”stylesheet” href=”{{static_url(‘CSS/table.css’)}}”>
<link rel=”stylesheet” href=”{{static_url(‘CSS/bootstrap.min.css’)}}”>
</head>

<body>

<br><br>
<div align=”center”>
<div style=”width:800px”>

<table class=”table table-striped table-bordered table-condensed table-responsive”>
<thead id=”index”>
<tr>
{% for title in data[0] %}
<th>{{title}}</th>
{% end %}
</tr>
</thead>
<tbody id=”body”>
{% for line in data[1:] %}
<tr>
{% for cell in line %}
<td>{{cell}}</td>
{% end %}
</tr>
{% end %}
</tbody>
</table>
</div>
<a href=”/file”><button class=”btn btn-warning” id=”review”> 文件上传界面 </button></a>
</div>

</body>
</html>
该界面主要用于显示表格文件中的数据,比如刚才上传成功的 Excel 文件,其中的数据如下:

  仅有 HTML 页面是不够的,我们还需要 Python 代码来控制网页的运行,这就是 server.py,其中的代码如下:
# -*- coding: utf-8 -*-

import xlrd
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options

# 定义端口为 12306
define(“port”, default=12306, help=”run on the given port”, type=int)

class UploadFileHandler(tornado.web.RequestHandler):
# get 函数
def get(self):
self.render(‘upload.html’)

# post 函数
def post(self):
# 文件的存放路径
upload_path = os.path.join(os.path.dirname(__file__), ‘files’)
# 提取表单中‘name’为‘file’的文件元数据
file_metas = self.request.files[‘file’]
for meta in file_metas:
filename = meta[‘filename’]
filepath = os.path.join(upload_path, filename)
# 有些文件需要已二进制的形式存储,实际中可以更改
with open(filepath, ‘wb’) as up:
up.write(meta[‘body’])
self.write(“<br><br>”)
self.write(‘<p> 上传 %s 成功!</p>’ % filename)
self.write(‘<p><a href=”/file_review”><button> 查看全部文件 </button></a></p>’)

class FileReviewHandler(tornado.web.RequestHandler):
def get(self):
# 文件的存放路径
upload_path = os.path.join(os.path.dirname(__file__), ‘files’)
files = os.listdir(upload_path)
for file in files:
if os.path.isdir(file):
files.remove(file)

self.render(‘fileReview.html’, files=files)

class DataReviewHandler(tornado.web.RequestHandler):

def get(self):
filename = self.get_argument(‘file’)
print(filename)
# 文件的存放路径
upload_path = os.path.join(os.path.dirname(__file__), ‘files’)
file_path = os.path.join(upload_path, filename)

if filename.endswith(‘.csv’):
with open(file_path, “r”) as f:
data = f.readlines()
data = [line.strip().split(‘,’) for line in data]

elif filename.endswith(‘.xls’) or filename.endswith(‘.xlsx’):
tables = xlrd.open_workbook(file_path)
table = tables.sheets()[0] # 第一张表格
nrows = table.nrows

# 循环行列表数据
data = []
for i in range(nrows):
data.append(table.row_values(i))

else:
data = []

self.render(‘dataReview.html’, data=data)

# 主函数
def main():

# 开启 tornado 服务
tornado.options.parse_command_line()
# 定义 app
app = tornado.web.Application(
handlers=[(r’/file’, UploadFileHandler),
(r’/file_review’, FileReviewHandler),
(r’/data’, DataReviewHandler)
], # 网页路径控制
template_path=os.path.join(os.path.dirname(__file__), “templates”), # 模板路径
static_path=os.path.join(os.path.dirname(__file__), “static”), # 配置静态文件路径
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

main()
点击运行 server.py 文件,在浏览中输入“localhost:12306/file”就能看到刚才的文件上传的页面了。到此,我们就讲完了这个项目的结构,我们省去了 static 文件的讲述,因为这并不影响程序的运行,只是页面的样式会比较丑陋,如果您想获得较好的浏览效果,可以从该项目的 github 地址中下载 static 文件夹,不必再自己重头写起。
使用
  笔者提供了以下三种方式供读者使用该项目:

直接使用
github 使用
docker 使用

直接使用
  读者按照上面的讲解,自己写一个项目,拷贝 static 文件夹,然后点击运行 server.py,在浏览中输入“localhost:12306/file”就能使用该程序来浏览上传的表格了。
github 使用
  从该项目的 github 地址:https://github.com/percent4/c…,命令如下:
git init
git clone https://github.com/percent4/csv_file_review
然后安装必要的第三方模块:xlrd, tornado, 点击运行 server.py,在浏览中输入“localhost:12306/file”就能使用该程序来浏览上传的表格了。
docker 使用
  首先拉取 docker 镜像:
docker pull jclian91/dockertest:csv_file_review.2019.02.21.2312
然后运行该镜像:
docker run -p 12306:12306 -v $PWD/db:/root/csv_file_review/src/files -it c97f252cd6e8 bash
注意,-it 后面为刚才拉取的 docker 镜像的 ID, 需要将 ID 替换为你刚拉取的镜像 ID,运行端口为本机的 12306,上传的表格数据存放在 $PWD/db 路径下。进入虚拟机后,运行 server.py 即可启动服务,
[root@fbb2c3fb6ce1 src]# ls
__init__.py files server.py static templates
[root@fbb2c3fb6ce1 src]# python server.py
在浏览中输入“localhost:12306/file”就能使用该程序来浏览上传的表格了。
总结
  关于本项目的介绍就到这儿了,感谢大家阅读~  如您对本项目的源代码感兴趣,可参考网址:https://github.com/percent4/c…
注意:本人现已开通微信公众号:Python 爬虫与算法(微信号为:easy_web_scrape),欢迎大家关注哦~~

正文完
 0