6月16日 Django作业 文件解压缩统计行数
作业要求:

前端页面注意:


自己写的:
from django.shortcuts import render, HttpResponse
import zipfile
import re # Create your views here. def op_zip(zip_file):
zfile = zipfile.ZipFile(zip_file, 'r') zfile_name_list = zfile.namelist()
# zfile_name_list = list(filter(lambda x: re.findall('\.[a-z]+$', x), zfile_name_list))
# print(zfile_name_list)
# html_files = filter(lambda x: x.endswith('.html'), zfile_name_list)
# py_files = filter(lambda x: x.endswith('.py'), zfile_name_list)
# css_files = filter(lambda x: x.endswith('.css'), zfile_name_list)
# js_files = filter(lambda x: x.endswith('.js'), zfile_name_list) count_file = {'html': 0, 'py': 0, 'css': 0, 'js': 0}
for file_name in zfile.namelist():
# if file_name.endswith('.zip'):
# child_zip_file = zfile.getinfo(file_name)
# print(zipfile.is_zipfile(file_name))
#
# data = zfile.read(file_name)
# print(data)
# res = op_zip(child_zip_file)
# for k in res:
# count_file[k] += res[k] if file_name.endswith('.html'):
data = zfile.read(file_name)
data_list = data.decode('utf8').split('\r\n')
zhu = 0
html_count = 0
for line in data_list:
if line.startswith('//'):
continue
if line.startswith('<!--') or line.startswith('/*'):
zhu += 1
if line.endswith('-->') or line.endswith('*/'):
zhu -= 1
if zhu == 0:
html_count += 1
count_file['html'] += html_count
elif file_name.endswith('.py'):
data = zfile.read(file_name)
data_list = data.decode('utf8').split('\r\n')
zhu = 0
py_count = 0
for line in data_list:
if line.startswith('#'):
continue
if line.startswith("\'\'\'") or line.startswith('\"\"\"'):
zhu += 1
if line.endswith("\'\'\'") or line.endswith('\"\"\"'):
zhu -= 1
if zhu == 0 and line:
py_count += 1
count_file['py'] = py_count
elif file_name.endswith('.css'):
data = zfile.read(file_name)
data_list = data.decode('utf8').split('\r\n')
zhu = 0
css_count = 0
for line in data_list:
if line.startswith('//'):
continue
if line.startswith('/*'):
zhu += 1
if line.endswith('*/'):
zhu -= 1
if zhu == 0:
css_count += 1
count_file['css'] += css_count elif file_name.endswith('.js'):
data = zfile.read(file_name)
data_list = data.decode('utf8').split('\r\n')
zhu = 0
js_count = 0
for line in data_list:
if line.startswith('//'):
continue
if line.startswith('/*'):
zhu += 1
if line.endswith('*/'):
zhu -= 1
if zhu == 0:
js_count += 1
count_file['js'] += js_count
print(count_file)
return count_file def upload(request):
if request.method == 'POST':
name = request.POST.get('name')
upload_file = request.FILES.get('upload_file')
count_file = op_zip(upload_file)
print(count_file)
return render(request, 'result.html', {'name': name, 'result': count_file})
return render(request, 'upload.html')
存在的问题:
1、没有考虑到上传文件时,上传的文件类型是否是压缩包
2、只对zip类型的压缩包进行解压
3、忘记了shutil模块
4、过程中遇到的问题:
正则表达式几乎都忘记了,前端界面bootstrap用的也磕磕绊绊的 ,还是缺少练习
老师的答案:
from django.shortcuts import render, HttpResponse
import shutil
import os
import uuid
from django.conf import settings ACCEPT_FILE_TYPE = ["zip", "tar", "gztar", "rar"] # Create your views here. def upload(request):
if request.method == "POST":
# 拿到上传的文件对象
file_obj = request.FILES.get("code_file")
# prefix:前缀 suffix:后缀
# 将上传文件的文件名字 从右边按 '.'切割(最多切一次)
filename, suffix = file_obj.name.rsplit(".", maxsplit=1)
# 如果上传的文件类型不是可接受的,就直接返回错误提示
if suffix not in ACCEPT_FILE_TYPE:
return HttpResponse("上传文件必须是压缩文件")
# 上传文件的类型正确
# 在项目的根目录下新建一个和上传文件同名的文件
with open(file_obj.name, "wb") as f:
# 从上传文件对象一点一点读取数据
for chunk in file_obj.chunks():
# 将数据写入我新建的文件
f.write(chunk)
# 拼接得到上传文件的全路径
real_file_path = os.path.join(settings.BASE_DIR, file_obj.name)
# 对上传的文件做处理
upload_path = os.path.join(settings.BASE_DIR, "files", str(uuid.uuid4()))
# 解压代码文件至指定文件夹
shutil.unpack_archive(real_file_path, extract_dir=upload_path)
# 代码行数统计
total_num = 0
for (dir_path, dir_names, filenames) in os.walk(upload_path):
# dir_path: 根目录 dir_names: 文件夹 filenames: 文件
# 遍历所有的文件
for filename in filenames:
# 将文件名和根目录拼接成完整的路径
file_path = os.path.join(dir_path, filename)
# 完整的路径按照'.' 进行右切割 (最大切割一次)
file_path_list = file_path.rsplit(".", maxsplit=1)
# 文件没有后缀名直接跳过
if len(file_path_list) != 2:
continue
# 如果不是py文件直接跳过
if file_path_list[1] != "py":
continue
# 初始化一个存放当前文件代码行数的变量
line_num = 0
with open(file_path, "r", encoding="utf8") as f:
# 一行一行读取
for line in f:
# 如果是注释就跳过
if line.strip().startswith("#"):
continue
# 否则代码行数+1
line_num += 1
total_num += line_num
return render(
request,
"show.html",
{"file_name": file_obj.name, "file_size": file_obj.size, "total_num": total_num, "value": "张曌"})
return render(request, "upload.html")
6月16日 Django作业 文件解压缩统计行数的更多相关文章
- 20.Nodejs基础知识(上)——2019年12月16日
2019年12月16日18:58:55 2019年10月04日12:20:59 1. nodejs简介 Node.js是一个让JavaScript运行在服务器端的开发平台,它让JavaScript的触 ...
- 16.go语言基础学习(上)——2019年12月16日
2019年12月13日10:35:20 1.介绍 2019年10月31日15:09:03 2.基本语法 2.1 定义变量 2019年10月31日16:12:34 1.函数外必须使用var定义变量 va ...
- 11月16日《奥威Power-BI基于SQL的存储过程及自定义SQL脚本制作报表》腾讯课堂开课啦
上周的课程<奥威Power-BI vs微软Power BI>带同学们全面认识了两个Power-BI的使用情况,同学们已经迫不及待想知道这周的学习内容了吧!这周的课程关键词—— ...
- 2016年12月16日 星期五 --出埃及记 Exodus 21:11
2016年12月16日 星期五 --出埃及记 Exodus 21:11 If he does not provide her with these three things, she is to go ...
- 2016年11月16日 星期三 --出埃及记 Exodus 20:7
2016年11月16日 星期三 --出埃及记 Exodus 20:7 "You shall not misuse the name of the LORD your God, for the ...
- 2016年10月16日 星期日 --出埃及记 Exodus 18:27
2016年10月16日 星期日 --出埃及记 Exodus 18:27 Then Moses sent his father-in-law on his way, and Jethro returne ...
- 12月16日广州.NET俱乐部下午4点爬白云山活动
正如我们在<广州.NET微软技术俱乐部与其他技术群的区别>和<广州.NET微软技术俱乐部每周三五晚周日下午爬白云山活动>里面提到的, 我们会在每周三五晚和周日下午爬白云山. ...
- 9月16日,base 福州,2018MAD技术论坛邀您一起探讨最前沿AR技术!
“ 人工智能新一波浪潮带动了语音.AR等技术的快速发展,随着智能手机和智能设备的普及,人机交互的方式也变得越来越自然. 9月16日,由网龙网络公司.msup联合主办的MAD技术论坛将在福州举行.本次论 ...
- 成都Uber优步司机奖励政策(4月16日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
随机推荐
- Solution -「多校联训」查拉图斯特拉如是说
\(\mathcal{Description}\) Link. 给定 \(n\) 和 \(m\) 次多项式 \(f(x)\),求 \[\sum_{i=0}^n\binom{n}{i}f(i)\ ...
- OpenHarmony移植案例与原理:startup子系统之syspara_lite系统属性部件
摘要:本文介绍下移植开发板时如何适配系统属性部件syspara_lite,并介绍下相关的运行机制原理. 本文分享自华为云社区<openharmony移植案例与原理 - startup子系统之sy ...
- Elasticsearch 7.12 启用 x-pack 组件
文章目录 修改配置文件 设置密码 使用密码 首先,你要有一套es,关于es的部署,可以看我的另一篇博客 ELK-EFK-v7.12.0日志平台部署 $ ./bin/elasticsearch-plug ...
- kali linux更新msf 报错Unable to find a spec satisfying metasploit-framework (>= 0) in the set. Perhaps the解决办法
首先换更新源 :vim /etc/apt/sources.list deb http://mirrors.ustc.edu.cn/kali kali-rolling main non-free co ...
- Java8新特性系列-Lambda
转载自:Java8新特性系列-Lambda – 微爱博客 Lambda Expressions in Java 8 Lambda 表达式是 Java 8 最流行的特性.它们将函数式编程概念引入 Jav ...
- 案例八:shell自动化管理账本脚本
该脚本目的帮助管理员创建账号.删除账号.锁定账号.解锁账号. #!/bin/bash #filename: #author: #date:2018-6-6 echo "用户管理程序" ...
- 【windows 操作系统】窗口指针 和 窗口句柄 有什么区别
句柄是指针的"指针" 指针对应着一个数据在内存中的地址,得到了指针就可以自由地修改该数据.Windows并不希望一般程序修改其内部数据结构,因为这样太不安全.所以Windows给每 ...
- java this 用法详解
一.JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法. 代码例子: public class ThisDemo { String name="Mic ...
- 知识增广的预训练语言模型K-BERT:将知识图谱作为训练语料
原创作者 | 杨健 论文标题: K-BERT: Enabling Language Representation with Knowledge Graph 收录会议: AAAI 论文链接: https ...
- WPS:公式在中间,编号靠右
1.新建表格1*3 2.在中间单元格内输入公式,在右边单元格中输入编号 3.在"开始"菜单栏找到"居中"和"靠右"两个按钮,给中间单元格设置 ...