Flask学习-设备管理系统3:从excel表导入设备信息_python flack开发设备管理列表-程序员宅基地

技术标签: python  

Flask学习-设备管理系统3:从excel表导入设备信息


本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.

环境
  • 主机:win10
  • python版本:python3.4
  • 开发环境:PyCharm5.0.2
说明

生产部有需求,从excel表格批量导入设备。

效果图

这里写图片描述

源代码
视图文件修改 view.py
    def open_excel(file= 'file.xls'):
        try:
            data = xlrd.open_workbook(file)
            return data
        except Exception as e:
            print (str(e))


    # 根据索引获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_index:表的索引
    def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0):
        data = open_excel(file)
        table = data.sheets()[by_index]
        nrows = table.nrows #行数
        ncols = table.ncols #列数
        colnames =  table.row_values(colnameindex) #某一行数据
        list =[]
        for rownum in range(1,nrows):

             row = table.row_values(rownum)
             if row:
                 app = {}
                 for i in range(len(colnames)):
                    app[colnames[i]] = row[i]
                 list.append(app)
        return list


    ALLOWED_EXTENSIONS = set(['xls', 'xlsx'])
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    @login_required
    @main.route('/import_device', methods=['GET', 'POST'])
    def import_device():
        if request.method == 'POST':
            file = request.files['file']
            filename = file.filename

            # 判断文件名是否合规
            if file and allowed_file(filename):
                file.save(os.path.join('.\\upload', filename))
            else:
                flash('失败:上传文件格式不对')
                return render_template('import_device.html')

            # file.save(os.path.join('c:\\mnt', filename))
            # file.save(os.path.join('.\\upload', filename))

            # 添加到数据库
            tables = excel_table_byindex(file='.\\upload\\' + filename)
            for row in tables:
                # 判断表格式是否对
                if '手持机DEVICEID' not in row or \
                    '手持机SIMID' not in row or \
                    '手持机硬件版本' not in row or \
                    '手持机软件版本' not in row or \
                    '脚扣DEVICEID' not in row or \
                    '脚扣SIMID' not in row or \
                    '脚扣硬件版本' not in row or \
                    '脚扣软件版本' not in row:
                    flash('失败:excel表格式不对')
                    return render_template('import_device.html')

                # print('0x%04x' % int(str(row['手持机DEVICEID']).split('.')[0], base=16))
                # 判断手持机字段是否存在
                if row['手持机DEVICEID'] != '' and row['手持机SIMID'] != '' and \
                    row['手持机硬件版本'] != '' and row['手持机软件版本'] != '':
                    id_format = '0x%04x' % int(str(row['手持机DEVICEID']).split('.')[0], base=16)
                    device = Device(device_type='手持机',
                                    device_id=id_format,
                                    device_simid=str(row['手持机SIMID']).split('.')[0],
                                    hard_version=int(row['手持机硬件版本']),
                                    soft_version=int(row['手持机软件版本']),
                                    warehouse=False,
                                    shipment_time='无',
                                    agent='无',
                                    prison='无',
                                    shutdown=False)
                    # 判断是否id重复
                    flag = True
                    if Device.query.filter_by(device_id=device.device_id).count() > 0:
                        flash('失败:设备ID:%s已存在' %device.device_id)
                        flag = False
                    # 判断simid是否重复
                    elif Device.query.filter_by(device_simid=device.device_simid).count() > 0:
                        flash('失败:设备SIMID:%s已存在' %device.device_simid)
                        flag = False
                    if flag:
                        db.session.add(device)
                    else:
                        return render_template('import_device.html')

                if row['脚扣DEVICEID'] != '' and row['脚扣SIMID'] != '' and \
                    row['脚扣硬件版本'] != '' and row['脚扣软件版本'] != '':
                    id_format = '0x%04x' % int(str(row['脚扣DEVICEID']).split('.')[0], base=16)
                    device = Device(device_type='脚扣',
                                    device_id=id_format,
                                    device_simid=str(row['脚扣SIMID']).split('.')[0],
                                    hard_version=int(row['脚扣硬件版本']),
                                    soft_version=int(row['脚扣软件版本']),
                                    warehouse=False,
                                    shipment_time='无',
                                    agent='无',
                                    prison='无',
                                    shutdown=False)
                    # 判断是否id重复
                    flag = True
                    if Device.query.filter_by(device_id=device.device_id).count() > 0:
                        flash('失败:设备ID:%s已存在' %device.device_id)
                        flag = False
                    # 判断simid是否重复
                    elif Device.query.filter_by(device_simid=device.device_simid).count() > 0:
                        flash('失败:设备SIMID:%s已存在' %device.device_simid)
                        flag = False
                    if flag:
                        db.session.add(device)
                    else:
                        return render_template('import_device.html')
            return redirect(url_for('.index'))

        return render_template('import_device.html')    
新建网页文件 import_device.html
    {% extends "base.html" %}
    {% import "bootstrap/wtf.html" as wtf %}

    {% block title %}外出押解设备管理系统 by jdh{% endblock %}

    {% block page_content %}
    <div class="page-header">
        <h1>导入设备信息</h1>
    </div>
    {#<div class="col-md-4">#}
    {#    {
   { wtf.quick_form(form) }}#}
    {#</div>#}
    <div class="col-md-4">
        <form action="" method=post enctype=multipart/form-data>
            <input type=file name=file><br/>
            <input type=submit value=Upload>
        </form>
    </div>
    {#<form class="well form-inline" method="POST">#}
    {#    {
   { form.hidden_tag() }}#}
    {#    <input type=file name=file>#}
    {#         <input type=submit value=Upload>#}
    {##}
    {#    {
   { form.name() }}#}
    {#    <button type="submit" class="btn">{
   { form.submit() }}</button>#}
    {#</form>#}

    {% endblock %}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/jdh99/article/details/51635507

智能推荐

干货!设计师必备的行业需求网站|有效提高工作效率!_行业市场需求网站-程序员宅基地

文章浏览阅读495次。设计,是一门庞大的学科它包罗万象,涉及生产、生活各个领域广义的设计分为:传统工艺品设计工业设计,视觉传达设计,环境艺术设计数字艺术设计,建筑设计,服装设计等等对于设计师来说,构思和创意固然重要提高工作效率,网站资源也是必不可少大概包括素材网站模板、灵感网站两大类资源一、素材网站模板:www.uppsd.com 优图网 电商美工必收藏的网站。www.sotu114.com 搜图114 专供PNG免扣素材的图片网站www.sucai63.com 素材路上 新媒_行业市场需求网站

Webpack4 配置copy-webpack-plugin^6.0.3的ignore_webpack4 使用copy-webpack-plugin哪个版本-程序员宅基地

文章浏览阅读1.6k次。我的版本 copy-webpack-plugin: ^6.0.3const CopyWebpackPlugin = require('copy-webpack-plugin');plugins: [ new CopyWebpackPlugin({ patterns: [{ from: path.join(__dirname,'../static'), to: 'static', globOptions: {_webpack4 使用copy-webpack-plugin哪个版本

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connec-程序员宅基地

文章浏览阅读4w次,点赞79次,收藏156次。WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘ProxyError(‘Cannot connect to proxy.’, OSError(0, ‘Error’))’:问题描述:pip 无论下载什么包的时候,就会出现4次:WARNING: Retrying (Retry(total=4, connect=None, r_warning: retrying (retry(total=4, connect=none, read=none, redirect=none, st

PlantUML绘制类图_plantuml画类图-程序员宅基地

文章浏览阅读6k次,点赞4次,收藏32次。类图是描述类、接口以及它们之间的静态关系图;本文主要介绍如何使用PlantUML 绘制类图_plantuml画类图

猫狗案例分析,实例及测试_定义猫类cat。属性:毛的颜色color,品种breed。行为:吃饭eat(),抓老鼠catchmo-程序员宅基地

文章浏览阅读982次。猫狗案例分析,实例及测试class Test05_Animal { public static void main(String[] args) { Cat c1 = new Cat("小蓝", 4); System.out.println(c1.getColor() + "..." + c1.getLeg()); c1.eat(); ..._定义猫类cat。属性:毛的颜色color,品种breed。行为:吃饭eat(),抓老鼠catchmouse()

android--彻底关闭--应用程序_android+os怎么关闭-程序员宅基地

文章浏览阅读860次。最近学习做android的游戏开发时候,发现一个关于android退出时不能彻底关闭的问题,比如:一个程序里new 出了N多个Thread,这样在退出程序的可能不能完全关闭,最后发现,只用finish()方法,有时候不能彻底退出,个人感觉还是要在适当的地方加上:System.exit(0);-=====-=-=-=-=-=======-----===== 1. finish_android+os怎么关闭

随便推点

Flutter ListView如何添加HeaderView和FooterView_flutter listview footerview-程序员宅基地

文章浏览阅读4.5k次。做过Android开发的同学知道,Android的ListView提供addHeaderView和addFooterView两个方法用于添加View到ListView;RecyclerView则通过定义不同的ItemType区分HeaderViewItem和普通的ListItem,在Adapter中加上逻辑判断返回对应的ViewHolder,处理起来还是有点麻烦的。而flutter的List..._flutter listview footerview

IP SLA_icmp、udp、jitter、VoIP-程序员宅基地

文章浏览阅读3.1k次,点赞2次,收藏8次。SLASLA:service level agreements服务等级协议cisco IOS SLA让用户可以监测两台思科路由器之间或思科路由器与一个远程IP设备之间的网络性能。Cisco公司提出来的一个用于测量网络质量的方法。IP SLA用途SLA监测网络性能监测网络服务评估端到端的可用性监测网络故障诊断MPLS网络监测VOIP网络监测IP SLA优点增强部署新应用的信..._ip sla

LeetCode 416. 分割等和子集 做题小结_分割等和子集 给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子-程序员宅基地

文章浏览阅读8.1k次。题目给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。注意:每个数组中的元素不会超过 100数组的大小不会超过 200示例 1:输入: [1, 5, 11, 5]输出: true解释: 数组可以分割成 [1, 5, 5] 和 [11]. 示例 2:输入: [1, 2, 3, 5]输出: false解释: 数组不能分割成两个元素和相等的子集.代码class Solution { public boolean _分割等和子集 给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子

初学驱动开发-windows驱动-命令行编译环境_windows怎么通过命令行编译驱动程序-程序员宅基地

文章浏览阅读3.8k次。1.下载并安装WDK76002.打开开始菜单Windows Driver Kits\WDK 7600.16385.1\...3.(配置临时环境路径)新建setIncludeXP.bat编辑内容 其中paths值为wdk安装文件对应的一个是头文件,一个是库文件位置set paths=D:\WinDDK\7600.16385.1\increm set include=%inclu_windows怎么通过命令行编译驱动程序

uboot通过tftp下载镜像文件_boot镜像文件下载-程序员宅基地

文章浏览阅读8.4k次。有时候我们可以通过uboot的tftp服务下载内核镜像并运行,从而完成对内核驱动的调试;本文将介绍这种方式的环境搭建:一、在宿主机端配置tftp服务1、安装$ apt-get install tftp-hpa tftpd-hpa xinetd注:在此说明,tftp-hpa和tftpd-hpa为tftp的客户端和服务端的软件包,而这两个软件包在之前的ubuntu版本中是tftp tf_boot镜像文件下载

Mysql -MVCC多版本并发控制机制_mysql mvcc管理-程序员宅基地

文章浏览阅读268次。MVCC多版本并发控制机制什么是MVCCMVCC的作用MVCC还涉及到RR、RC等相关问题什么是MVCCMVCC,全称Multi-Version Concurrency Control,即多版本并发控制。MVCC是一种并发控制的方法,一般在数据库管理系统中,实现对数据库的并发访问,在编程语言中实现事务内存。MVCC的作用Mysql在可重复读隔离级别下如何保证事务较高的隔离性,同样的sql查询语句在一个事务里多次执行查询结果相同,就算其它事务对数据有修改也不会影响当前事务sql语句的查询结果。这_mysql mvcc管理