舉例講解Python的Tornado框架實現(xiàn)數(shù)據(jù)可視化的教程
所用拓展模塊
xlrd:
Python語言中,讀取Excel的擴展工具??梢詫崿F(xiàn)指定表單、指定單元格的讀取。
使用前須安裝。
下載地址:https://pypi.python.org/pypi/xlrd
解壓后cd到解壓目錄,執(zhí)行 python setup.py install 即可
datetime:
Python內(nèi)置用于操作日期時間的模塊
擬實現(xiàn)功能模塊
讀xls文件并錄入數(shù)據(jù)庫
根據(jù)年、月、日三個參數(shù)獲取當天的值班情況
餅狀圖(當天完成值班任務人數(shù)/當天未完成值班任務人數(shù))
瀑布圖(當天所有值班人員的值班情況)
根據(jù)年、月兩個參數(shù)獲取當月的值班情況
根據(jù)年參數(shù)獲取當年的值班情況
值班制度
每天一共有6班:
8:00 - 9:45
9:45 - 11:20
13:30 - 15:10
15:10 - 17:00
17:00 - 18:35
19:00 - 22:00
每個人每天最多值一班。
僅值班時間及前后半個小時內(nèi)打卡有效。
上班、下班均須打卡,缺打卡則視為未值班。
分析Excel表格
我的指紋考勤機可以一次導出最多一個月的打卡記錄。有一個問題是,這一個月可能橫跨兩個月,也可能橫跨一年。比如:2015年03月21日-2015年04月20日、2014年12月15日-2015年01月05日。所以寫處理方法的時候一定要注意這個坑。
導出的表格如圖所示:

=。=看起來好像基本沒人值班,對,就是這樣。
大家都好懶T。T
Sign...
簡單分析一下,
- 考勤記錄表是文件的第三個sheet
- 第三行有起止時間
- 第四行是所有日期的數(shù)字
- 接下來每兩行:第一行為用戶信息;第二行為考勤記錄
思路
決定用3個collection分別儲存相關信息:
- user:用戶信息,包含id、name、dept
- record:考勤記錄,包含id(用戶id)、y(年)、m(月)、d(日)、check(打卡記錄)
- duty:值班安排,包含id(星期數(shù),例:1表示星期一)、list(值班人員id列表)、user_id:["start_time","end_time"](用戶值班開始時間和結(jié)束時間)
讀取xls文件,將新的考勤記錄和新的用戶存入數(shù)據(jù)庫。
根據(jù)年月日參數(shù)查詢對應record,查詢當天的值班安排,匹配獲得當天值班同學的考勤記錄。將值班同學的打卡時間和值班時間比對,判斷是否正常打卡,計算實際值班時長、實際值班百分比。
之后輸出json格式數(shù)據(jù),用echarts生成圖表。
分析當月、當年的考勤記錄同理,不過可能稍微復雜一些。
所有的講解和具體思路都放在源碼注釋里,請繼續(xù)往下看源碼吧~
源碼
main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import pymongo
import time
import datetime
import xlrd
define("port", default=8007, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/read", ReadHandler),
(r"/day", DayHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
)
conn = pymongo.Connection("localhost", 27017)
self.db = conn["kaoqin"]
tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
pass
class ReadHandler(tornado.web.RequestHandler):
def get(self):
#獲取collection
coll_record = self.application.db.record
coll_user = self.application.db.user
#讀取excel表格
table = xlrd.open_workbook('/Users/ant/Webdev/python/excel/data.xls')
#讀取打卡記錄sheet
sheet=table.sheet_by_index(2)
#讀取打卡月份范圍
row3 = sheet.row_values(2)
m1 = int(row3[2][5:7])
m2 = int(row3[2][18:20])
#設置當前年份
y = int(row3[2][0:4])
#設置當前月份為第一個月份
m = m1
#讀取打卡日期范圍
row4 = sheet.row_values(3)
#初始化上一天
lastday = row4[0]
#遍歷第四行中的日期
for d in row4:
#如果日期小于上一個日期
#說明月份增大,則修改當前月份為第二個月份
if d < lastday:
m = m2
#如果當前兩個月份分別為12月和1月
#說明跨年了,所以年份 +1
if m1 == 12 and m2 == 1:
y = y + 1
#用n計數(shù),范圍為 3 到(總行數(shù)/2+1)
#(總行數(shù)/2+1)- 3 = 總用戶數(shù)
#即遍歷所有用戶
for n in range(3, sheet.nrows/2+1):
#取該用戶的第一行,即用戶信息行
row_1 = sheet.row_values(n*2-2)
#獲取用戶id
u_id = row_1[2]
#獲取用戶姓名
u_name = row_1[10]
#獲取用戶部門
u_dept = row_1[20]
#查詢該用戶
user = coll_user.find_one({"id":u_id})
#如果數(shù)據(jù)庫中不存在該用戶則創(chuàng)建新用戶
if not user:
user = dict()
user['id'] = u_id
user['name'] = u_name
user['dept'] = u_dept
coll_user.insert(user)
#取該用戶的第二行,即考勤記錄行
row_2 = sheet.row_values(n*2-1)
#獲取改當前日期的下標
idx = row4.index(d)
#獲取當前用戶當前日期的考勤記錄
check_data = row_2[idx]
#初始化空考勤記錄列表
check = list()
#5個字符一組,遍歷考勤記錄并存入考勤記錄列表
for i in range(0,len(check_data)/5):
check.append(check_data[i*5:i*5+5])
#查詢當前用戶當天記錄
record = coll_record.find_one({"y":y, "m":m, "d":d, "id":user['id']})
#如果記錄存在則更新記錄
if record:
for item in check:
#將新的考勤記錄添加進之前的記錄
if item not in record['check']:
record['check'].append(item)
coll_record.save(record)
#如果記錄不存在則插入新紀錄
else:
record = {"y":y, "m":m, "d":d, "id":user['id'], "check":check}
coll_record.insert(record)
class DayHandler(tornado.web.RequestHandler):
def get(self):
#獲取年月日參數(shù)
y = self.get_argument("y",None)
m = self.get_argument("m",None)
d = self.get_argument("d",None)
#判斷參數(shù)是否設置齊全
if y and m and d:
#將參數(shù)轉(zhuǎn)換為整型數(shù),方便使用
y = int(y)
m = int(m)
d = int(d)
#獲取當天所有記錄
coll_record = self.application.db.record
record = coll_record.find({"y":y, "m":m, "d":d})
#獲取當天為星期幾
weekday = datetime.datetime(y,m,d).strftime("%w")
#獲取當天值班表
coll_duty = self.application.db.duty
duty = coll_duty.find_one({"id":int(weekday)})
#初始化空目標記錄(當天值班人員記錄)
target = list()
#遍歷當天所有記錄
for item in record:
#當該記錄的用戶當天有值班任務時,計算并存入target數(shù)組
if int(item['id']) in duty['list']:
#通過用戶id獲取該用戶值班起止時間
start = duty[item['id']][0]
end = duty[item['id']][1]
#計算值班時長/秒
date1 = datetime.datetime(y,m,d,int(start[:2]),int(start[-2:]))
date2 = datetime.datetime(y,m,d,int(end[:2]),int(end[-2:]))
item['length'] = (date2 - date1).seconds
#初始化實際值班百分比
item['per'] = 0
#初始化上下班打卡時間
item['start'] = 0
item['end'] = 0
#遍歷該用戶打卡記錄
for t in item['check']:
#當比值班時間來得早
if t < start:
#計算時間差
date1 = datetime.datetime(y,m,d,int(start[:2]),int(start[-2:]))
date2 = datetime.datetime(y,m,d,int(t[:2]),int(t[-2:]))
dif = (date1 - date2).seconds
#當打卡時間在值班時間前半小時內(nèi)
if dif <= 1800:
#上班打卡成功
item['start'] = start
elif t < end:
#如果還沒上班打卡
if not item['start']:
#則記錄當前時間為上班打卡時間
item['start'] = t
else:
#否則記錄當前時間為下班打卡時間
item['end'] = t
else:
#如果已經(jīng)上班打卡
if item['start']:
#計算時間差
date1 = datetime.datetime(y,m,d,int(end[:2]),int(end[-2:]))
date2 = datetime.datetime(y,m,d,int(t[:2]),int(t[-2:]))
dif = (date1 - date2).seconds
#當打卡時間在值班時間后半小時內(nèi)
if dif <= 1800:
#下班打卡成功
item['end'] = end
#當上班下班均打卡
if item['start'] and item['end']:
#計算實際值班時長
date1 = datetime.datetime(y,m,d,int(item['start'][:2]),int(item['start'][-2:]))
date2 = datetime.datetime(y,m,d,int(item['end'][:2]),int(item['end'][-2:]))
dif = (date2 - date1).seconds
#計算(實際值班時長/值班時長)百分比
item['per'] = int(dif/float(item['length']) * 100)
else:
#未正常上下班則視為未值班
item['start'] = 0
item['end'] = 0
#將記錄添加到target數(shù)組中
target.append(item)
#輸出數(shù)據(jù)
self.render("index.html",
target = target
)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
index.html
{
{% for item in target %}
{
'id':{{ item['id'] }},
'start':{{ item['start'] }},
'end':{{ item['end'] }},
'length':{{ item['length'] }},
'per':{{ item['per'] }}
}
{% end %}
}
最后
暫時只寫到讀文件和查詢某天值班情況,之后會繼續(xù)按照之前的計劃把這個小應用寫完的。
因為涉及到一堆小伙伴的隱私,所以沒有把測試文件發(fā)上來。不過如果有想實際運行看看的同學可以跟我說,我把文件發(fā)給你。
可能用到的一條數(shù)據(jù)庫插入語句:db.duty.insert({"id":5,"list":[1,2],1:["19:00","22:00"],2:["19:00","22:00"]})
希望對像我一樣的beginner們有幫助!
- 利用Python繪制MySQL數(shù)據(jù)圖實現(xiàn)數(shù)據(jù)可視化
- 利用Python代碼實現(xiàn)數(shù)據(jù)可視化的5種方法詳解
- Python數(shù)據(jù)可視化正態(tài)分布簡單分析及實現(xiàn)代碼
- 利用Python進行數(shù)據(jù)可視化常見的9種方法!超實用!
- 基于Python數(shù)據(jù)可視化利器Matplotlib,繪圖入門篇,Pyplot詳解
- Python實現(xiàn)數(shù)據(jù)可視化看如何監(jiān)控你的爬蟲狀態(tài)【推薦】
- 以911新聞為例演示Python實現(xiàn)數(shù)據(jù)可視化的教程
- Python數(shù)據(jù)可視化編程通過Matplotlib創(chuàng)建散點圖代碼示例
- Python數(shù)據(jù)可視化庫seaborn的使用總結(jié)
- python地震數(shù)據(jù)可視化詳解
相關文章
Django shell調(diào)試models輸出的SQL語句方法
今天小編就為大家分享一篇Django shell調(diào)試models輸出的SQL語句方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python使用ThreadPoolExecutor一次開啟多個線程
通過使用ThreadPoolExecutor,您可以同時開啟多個線程,從而提高程序的并發(fā)性能,本文就來介紹一下Python使用ThreadPoolExecutor一次開啟多個線程,感興趣的可以了解一下2023-11-11
Python?Bleach保障網(wǎng)絡安全防止網(wǎng)站受到XSS(跨站腳本)攻擊
Bleach?不僅可以清理?HTML?文檔,還能夠?qū)︽溄舆M行處理,檢查是否是合法格式,并可以使用白名單來控制哪些?HTML?標簽、屬性是安全的,因此非常適合用于清潔用戶輸入的數(shù)據(jù),確保網(wǎng)站安全2024-01-01
python通過urllib2獲取帶有中文參數(shù)url內(nèi)容的方法
這篇文章主要介紹了python通過urllib2獲取帶有中文參數(shù)url內(nèi)容的方法,涉及Python中文編碼的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
Python自動化操作Excel方法詳解(xlrd,xlwt)
Excel是Windows環(huán)境下流行的、強大的電子表格應用。本文將詳解用Python利用xlrd和xlwt實現(xiàn)自動化操作Excel的方法詳細,需要的可以參考一下2022-06-06

