舉例講解Python的Tornado架構實現資料視覺效果的教程

來源:互聯網
上載者:User
所用拓展模組

xlrd:

Python語言中,讀取Excel的擴充工具。可以實現指定表單、指定儲存格的讀取。
使用前須安裝。
下載地址:https://pypi.python.org/pypi/xlrd
解壓後cd到解壓目錄,執行 python setup.py install 即可

datetime:

Python內建用於操作日期時間的模組

擬實現功能模組

讀xls檔案並錄入資料庫

根據年、月、日三個參數擷取當天的值班情況

餅狀圖(當天完成值班任務人數/當天未完成值班任務人數)

瀑布圖(當天所有值班人員的值班情況)

根據年、月兩個參數擷取當月的值班情況

根據年參數擷取當年的值班情況

值班制度

每天一共有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

每個人每天最多值一班。

僅值班時間及前後半個小時內打卡有效。

上班、下班均須打卡,缺打卡則視為未值班。

分析Excel表格

我的指紋考勤機可以一次匯出最多一個月的打卡記錄。有一個問題是,這一個月可能橫跨兩個月,也可能橫跨一年。比如:2015年03月21日-2015年04月20日、2014年12月15日-2015年01月05日。所以寫處理方法的時候一定要注意這個坑。

匯出的表格:


=。=看起來好像基本沒人值班,對,就是這樣。
大家都好懶T。T
Sign...

簡單分析一下,

  • 考勤記錄表是檔案的第三個sheet
  • 第三行有起止時間
  • 第四行是所有日期的數字
  • 接下來每兩行:第一行為使用者資訊;第二行為考勤記錄

思路

決定用3個collection分別儲存相關資訊:

  1. user:使用者資訊,包含id、name、dept
  2. record:考勤記錄,包含id(使用者id)、y(年)、m(月)、d(日)、check(打卡記錄)
  3. duty:值班安排,包含id(星期數,例:1表示星期一)、list(值班人員id列表)、user_id:["start_time","end_time"](使用者值班開始時間和結束時間)

讀取xls檔案,將新的考勤記錄和新的使用者存入資料庫。

根據年月日參數查詢對應record,查詢當天的值班安排,匹配獲得當天值班同學的考勤記錄。將值班同學的打卡時間和值班時間比對,判斷是否正常打卡,計算實際值班時間長度、實際值班百分比。

之後輸出json格式資料,用echarts組建圖表。

分析當月、當年的考勤記錄同理,不過可能稍微複雜一些。

所有的講解和具體思路都放在源碼注釋裡,請繼續往下看源碼吧~

源碼

main.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import os.pathimport tornado.authimport tornado.escapeimport tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado.options import define, optionsimport pymongoimport timeimport datetimeimport xlrddefine("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):    passclass 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計數,範圍為 3 到(總行數/2+1)      #(總行數/2+1)- 3 = 總使用者數      #即遍曆所有使用者      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})        #如果資料庫中不存在該使用者則建立新使用者        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):    #擷取年月日參數    y = self.get_argument("y",None)    m = self.get_argument("m",None)    d = self.get_argument("d",None)    #判斷參數是否設定齊全    if y and m and d:      #將參數轉換為整型數,方便使用      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數組        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              #當打卡時間在值班時間前半小時內              if dif <= 1800:                #上班打卡成功                item['start'] = start            elif t < end:              #如果還沒上班打卡              if not item['start']:                #則記錄目前時間為上班打卡時間                item['start'] = t              else:                #否則記錄目前時間為下班打卡時間                item['end'] = t            else:              #如果已經上班打卡              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                #當打卡時間在值班時間後半小時內                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數組中          target.append(item)      #輸出資料      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 %}}

最後

暫時唯寫到讀檔案和查詢某天值班情況,之後會繼續按照之前的計劃把這個小應用寫完的。

因為涉及到一堆小夥伴的隱私,所以沒有把測試檔案發上來。不過如果有想實際運行看看的同學可以跟我說,我把檔案發給你。

可能用到的一條資料庫插入語句:db.duty.insert({"id":5,"list":[1,2],1:["19:00","22:00"],2:["19:00","22:00"]})

希望對像我一樣的beginner們有協助!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.