用django统计代码行数+注释行数

时间:2023-03-08 16:24:48
用django统计代码行数+注释行数

实现统计代码行数:

1、首先在url.py中配置

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', views.upload), ]

2、写视图函数:实现统计代码的行数以及注释行数,其中以.py文件为例,注释是以“#”或者““”“”“””开头的,去掉空格

from django.shortcuts import render,redirect

# Create your views here.

def upload(request):
if request.method == "POST":
file_obj = request.FILES.get("file")
with open(file_obj.name, "wb") as f:
for chunk in file_obj.chunks():
f.write(chunk)
# 已经将文件保存在服务端,现在开始进行代码统计
code_line = 0
comment_line = 0
flag = False
with open(file_obj.name, "r", encoding="utf-8") as f2:
for line in f2:
if line.strip():
if flag and not line.strip().startswith('"""'):
comment_line += 1
else:
if line.strip().startswith("#"):
comment_line += 1
elif line.strip().startswith('"""'):
if not flag:
flag = True
else:
flag = False
comment_line += 1
else:
code_line += 1
return render(request, "show.html", {"filename": file_obj.name, "code_line": code_line, "comment_line": comment_line})
return render(request, "upload.html")

3、写html代码:

upload.html的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传代码</title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group" style="margin-top: 40px;margin-left: 200px;">
<input type="file" name="file" id="exampleInputFile">
</div>
<button type="submit" class="btn btn-success" style="margin-left: 200px">提交</button>
</form>
</body>
</html>

show.html的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>代码数</title>
</head>
<body>
<ul style="margin-left: 200px;margin-top: 40px;">
<li>文件名:{{filename}}</li>
<li>代码行数:{{code_line}}</li>
<li>注释行数:{{comment_line}}</li>
</ul>
</body>
</html>

引入bootstrap样式的时候,一定要配置static:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]