Flask统计代码行数

流程:

  1.获取前端的文件

  2.判断文件是否zip文件

  3.解压压缩包并保存

  4.遍历解压后的文件夹

  5.判断文件是否py文件,将绝对路径添加到列表

  6.循环列表,排除注释和空号,统计行数

from flask import Blueprint
from flask import render_template
from flask import request
from flask import current_app
import time
import os
import shutil

uploadBlue = Blueprint("uploadBlue",__name__)

@uploadBlue.route("/upload",methods=["GET","POST"])
def upload():
    error = ""
    if request.method == "POST":
        # 获取前端的上传的文件
        file = request.files.get("file")
        # 判断后缀是否zip的文件
        zip_file = file.filename.rsplit(".",1)
        if zip_file[-1] != "zip":
            return render_template("upload.html", error="上传的不是zip文件,请重新上传")

        # 解压保存
        t = int(time.time())
        upload_path = os.path.join(current_app.config.root_path,"files",str(t))
        try:
            shutil._unpack_zipfile(file,upload_path)        # 解压文件
        except Exception as e:
            print(e)
            shutil.rmtree(upload_path)          # 删除非空文件夹
            return render_template("upload.html", error="文件解压异常")

        # 遍历保存的文件夹得到所有.py文件
        file_list = []
        for (dirpath,dirname,filenames) in os.walk(upload_path):
            # 判断文件是否py结尾,如果是则将绝对路径添加到列表
            for file in filenames:
                if file.rsplit(".",1)[-1] == "py":
                    file_path = os.path.join(upload_path,file)
                    file_list.append(file_path)
        num = 0
        for pyfile in file_list:
            with open(pyfile,mode='rb') as f:
                for line in f:
                    # 井号开头或者空行则跳过
                    if line.replace(b" ",b"").strip().startswith(b"#") or not line.strip():
                        continue
                    num += 1
        return str(num)

    return render_template("upload.html",error=error)

 

posted @ 2019-01-03 20:14  st--st  阅读(339)  评论(0编辑  收藏  举报