def upload(): if request.method == "GET": return render_template('upload.html') from werkzeug.datastructures import FileStorage file_obj = request.files.get('code') # 1. 检查上传文件后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) if len(name_ext) != 2: return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" # 2. 接收用户上传文件,并写入到服务器本地. # file_path = os.path.join("zips", file_obj.filename) # 从file_obj.stream中读取内容,写入到文件 # file_obj.save(file_path) # 3. 解压zip文件 import shutil # 通过open打开压缩文件,读取内容再进行解压。 # shutil._unpack_zipfile(file_path, 'files') target_path = os.path.join('files', str(uuid.uuid4())) shutil._unpack_zipfile(file_obj, target_path) ctime = datetime.date.today() file_name = file_obj.filename.split('.')[0] helper.insert( "insert into files_upload(file_name,target_path,user_id,ctime)values(%s,%s,%s,%s)", (file_name, target_path, session['user_info']['id'], ctime)) return "上传成功"
def upload(): try: if request.method=='GET': return render_template('upload.html') # from werkzeug.datastructures import FileStorage file_obj=request.files.get('code') name_ext=file_obj.filename.rsplit('.',maxsplit=1) if len(name_ext) !=2: return "请上传rar文件!" # if name_ext[1] !='rar': # return "请上传rar文件" # file_path=os.path.join('files',file_obj.filename) # print(file_path) # file_obj.save(file_path) import shutil,uuid target_path=os.path.join('files',str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream,target_path) total_num=0 for base_path,folder_list,file_list in os.walk(target_path): for file_name in file_list: file_path=os.path.join(base_path,file_name) file_ext=file_path.rsplit('.',maxsplit=1) if len(file_ext) !=2: continue if file_ext[1] !='py': continue file_num=0 with open(file_path,'rb') as f: for line in f: line=line.strip() if not line: continue if line.startswith(b'#'): continue file_num +=1 total_num +=file_num except Exception as e: return '请上传正确的文件格式' import datetime ctime=datetime.date.today() # conn=pymysql.Connection(host='127.0.0.1',port=3306,user='******',password='******',database='codeftp') # cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute("select id from record where datetime=%s and user_id=%s",(ctime,session['user_info']['id'])) # data=cursor.fetchall() # cursor.close() # conn.close() data=helper.fetch_all("select id from record where datetime=%s and user_id=%s",(ctime,session['user_info']['id'])) if data >2: return "今天已上传" # conn = pymysql.Connection(host='127.0.0.1', port=3306, user='******', password='******', database='codeftp') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute("insert into record(user_id,datetime,codeline) values(%s,%s,%s)",(session['user_info']['id'],ctime,total_num)) # conn.commit() # cursor.close() # conn.close() helper.insert("insert into record(user_id,datetime,codeline) values(%s,%s,%s)",(session['user_info']['id'],ctime,total_num)) return "上传成功"
def upload(): if request.method == 'GET': return render_template('upload.html') file_obj = request.files.get('code') # 1. 检查上传文件后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) if len(name_ext) != 2: return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" # 2+3, 接收用户上传文件,并解压到指定目录 import shutil target_path = os.path.join('files', str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream, target_path) # 4. 遍历某目录下的所有文件 total_num = 0 for base_path, folder_list, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num # 获取当前时间 import datetime ctime = datetime.date.today() print(total_num, ctime, session['user_info']['id']) data = helper.fetch_one( "select id from CODE_RECORD where date=%s and user=%s", (ctime, session['user_info']['id'])) if data: return "今天已经上传过了 请明天再试哦" helper.insert("insert into CODE_RECORD(count,date,user)values(%s,%s,%s)", (total_num, ctime, session['user_info']['id'])) return 'upload success, thank you '
def upload_code(): error = None if request.method == 'POST': # 1、上传的文件不能为空 if 'file' not in request.files: error = '需要上传文件' return render_template('codes/upload.html', error=error) file = request.files['file'] print(file.filename) # 文件名称 print(file.stream) # 文件内容 # 2、上传的文件格式必须符号要求 if file and allowed_file(file.filename): # 3、判断当前用户是否是首次上传 today_str = str(datetime.datetime.now())[:10] sql = 'select * from codes_upload where user=%s and upload_time=%s' % ( int(session.get('id', '')), "'" + today_str + "'") rets = sql_execute(sql) # print('查询结果:', rets) if not rets: # 4、接收用户上传文件并解压到指定的目录,生成随机文件夹名称,防止重名覆盖 # 注意必须确保上传的文件是以zip方式压缩的,单纯的修改zip后缀仍然不算zip格式 target_path = os.path.join(DevelopmentConfig.UPLOAD_FOLDER, str(uuid.uuid4())) shutil._unpack_zipfile(file.stream, target_path) # 6、遍历目录下的所有文件,并汇总出解压后的所有的文件的行数 total_num = 0 for root, dirs, files in os.walk(target_path): # print(dirs) # print(root) # 文件夹的绝对路径 for filename in files: line_count = 0 file_path = os.path.join(root, filename) with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line or line.startswith(b'#'): continue line_count += 1 total_num += line_count print(total_num) add_sql = 'insert into codes_upload (user,lines_num,upload_time) values (%s, %s, %s)' % ( session.get('id', ''), total_num, "'" + today_str + "'") rets = sql_execute(add_sql, type='insert') return redirect( url_for('co.my_uploads', nid=int(session.get('id')))) error = '今天代码已上传' else: error = '文件必须为zip格式' return render_template('codes/upload.html', error=error)
def push_file(): """ 处理用户提交文件 :return: """ try: uid = session.get("user").get('user') # 获得当前登录用户的uid 用于插入完成后数据库中提交数据 files = request.files.get("files") now_time = datetime.date.today() # 进行判断 是否该用户今天已经提交过代码 judgement_sql = "select id from details where username=%s and time=%s " ret = sql_fetchone(judgement_sql, (uid, now_time)) if ret: return "您今天已经提交过代码啦" files_suffix = files.filename.rsplit(".", maxsplit=1) # 从右向左 以"."进行切以分获得后缀名 if len(files_suffix) != 2: # 判断上传文件是否携带后缀 return "上传格式有误,请上传压缩的zip包" if files_suffix[1] != 'zip': # 判断上传文件是否是zip压缩文件 print("no zip") return "上传格式有误,请上传压缩的zip包" # 处理上传的zip文件 # 直接将zip文件解压至static_pull文件夹 文件地址 decompression_path = os.path.join('static_pull', str(uuid.uuid4())) shutil._unpack_zipfile(files, decompression_path) # 使用_unpack_zipfile 边读边压缩 # 压缩完成后 循环读每一个文件读取相应的行数 global_line = 0 for root, dirs, file in os.walk(decompression_path): # 判断每一个文件的后缀 for file_name in file: file_path = os.path.join(root, file_name) # 当前遍历到的文件路径 用于打开文件使用 file_suffix = file_name.rsplit(".", maxsplit=1) if len(file_suffix) != 2: # 如果没有后缀 则不处理 continue if file_suffix[1] != 'py': # 如果不是py文件 则不处理 continue line = 0 # 设置标记位 记录单个文件的行数 with open(file_path, 'rb') as f: for i in f: i = i.strip() if not i: # 如果是空行则不计算 continue if i.startswith(b'#'): continue line += 1 global_line += line sql = "insert into details(username,row,time) values (%s,%s,%s)" sql_commit(sql, (uid, global_line, now_time)) return "上传成功" except Exception as e: print(e) return "上传失败"
def upload(): if request.method == "GET": return render_template('upload.html') file_obj = request.files.get('code') if not file_obj: return render_template('upload.html') name_ext = file_obj.filename.rsplit('.', maxsplit=1) if len(name_ext) != 2: return "上传zip文件" if name_ext[1] != 'zip': return "上传zip文件" import shutil file_path = os.path.join("files", file_obj.filename) file_obj.save(file_path) target_path = os.path.join('files', str(uuid.uuid4())) shutil._unpack_zipfile(file_path, target_path) os.remove(file_path) # 删除zip文件 total_num = 0 for bath_path, folder_list, file_list in os.walk( target_path): # 文件路径, 包含的文件夹, 包含的文件 for file_name in file_list: file_path = os.path.join(bath_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue # 返回while, for 循环开头 if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() # stipt 为空时,默认删除空白符(包括'\n', '\r', '\t', ' ') if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num import datetime ctime = datetime.date.today() data = helper.fetch_one( "select id from record where ctime=%s and user_id=%s", (ctime, session['user_info']['id'])) if data: return render_template("ready.html") helper.insert( "insert into record(line,ctime,user_id)values(%s,%s,%s)", (total_num, ctime, session['user_info']['id'])) return render_template("seccess.html")
def uplosd(): """ 上传代码函数 :return: """ if request.method == 'GET': return render_template("upload.html") # 接收用户上传的文件 file = request.files.get('file') path, ext = file.filename.rsplit('.', maxsplit=1) # 检查是否是.zip压缩的文件 if ext != 'zip': return '仅支持上传.zip格式文件' # 存储到本地 uplosd_path = os.path.join('funk.config.root_path', 'files', str(uuid.uuid4())) # 解压文件 shutil._unpack_zipfile(file.stream, uplosd_path) total_num = 0 """ dirpath:当前所处位置路径 dirnames:当前所处位置有那几个文件夹 filenames:当前所处位置有哪些文件 """ for (dirpath, dirnames, filenames) in os.walk(uplosd_path): for filename in filenames: file_path = os.path.join(dirpath, filename) file_path_ext = file_path.rsplit('.', maxsplit=1) # 仅计算.py文件的行数 if len(file_path_ext) != 2: continue if file_path_ext[1] != 'py': continue line_num = 0 with open(file_path, mode='rb') as f: for line in f: if line.strip().startswith(b'#'): continue line_num += 1 total_num += line_num ctime = datetime.date.today() sql = 'select id from code WHERE ctime=%s and user_id = %s' ret = helper.fetch_one(sql, (ctime, session['user_info']['id'])) if ret: return "今日已经上传" sql = 'insert into code(line, ctime,user_id) VALUES (%s,%s,%s)' helper.insert(sql, (total_num, ctime, session['user_info']['id'])) return redirect('/user_list')
def code_upload(): if request.method == "POST": if check_upload(): flash('今天的代码已经上传了!', 'error') return render_template('home/upload_code.html') file_obj = request.files.get('code') # <FileStorage: '' ('application/octet-stream')>,把上传的东西方内存了 # print(file_obj.filename) # 上传的文件名(带扩展名) # print(file_obj.stream) # 文件的内容被封装到对象中 """ 1.检查上传文件的后缀名 """ filename_ext = file_obj.filename.rsplit('.', maxsplit=1) # 元组 msg = str() if len(filename_ext) != 2: msg = '请上传压缩文件!' return render_template('home/upload_code.html', msg=msg) if filename_ext[1] != 'zip': msg = '请上传后缀名为zip的文件' return render_template('home/upload_code.html', msg=msg) """ 2.接受用户上传的文件并写入到本地 """ if not os.path.exists('files'): os.mkdir('files') # 项目目录下,非app目录下 file_path = os.path.join('files', file_obj.filename) file_obj.save(file_path) # save的本质是:从file_obj.stream中读取内容写入到文件 """ 3.解压zip文件 """ import shutil target_path = os.path.join('files', str(uuid.uuid4())) # 允许上传的文件名相同 # print(target_path) # files/549fb0e2-924c-460d-a993-935fcc8e3274 # 通过open打开压缩文件,读取内容再进行解压 shutil._unpack_zipfile(file_path, target_path) # 2和3步合并,接受用户上传的文件,并解压至指定目录 # import shutil # shutil._unpack_zipfile(file_obj.stream, r'/home/thanlon/PycharmProjects/code_count/files') """ 5. 持久化到数据库 """ ctime = datetime.date.today() db_helper.insert('insert record(line,ctime,user_id) values(%s,%s,%s)', (get_code_line(target_path), ctime, session['user_info']['id'])) flash('上传成功!', 'ok') return render_template('home/upload_code.html')
def upfile(): """ 上传文件,并统计有效代码行数,写入数据库""" if request.method == 'GET': return render_template('push.html') # 获取上传文件 file = request.files.get('code') if file is None: return 'none' total_num = 0 # 检验文件后缀 name_split = file.filename.rsplit('.', maxsplit=1) if name_split[1] == 'py': total_num = count_row(file.stream) elif name_split[1] == 'zip': import shutil target_path = os.path.join('upfiles', str(uuid.uuid4())) shutil._unpack_zipfile(file.stream, target_path) for base_path, folder_list, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = count_row(file_path) total_num += file_num else: return render_template('push.html', err="您上传的文件格式不支持") # 获取当前时间 import datetime ctime = datetime.date.today() sql = "insert into coderec(uid,rownum,push_date) values (%s,%s,%s)" data = fetch_one("select id from coderec where push_date=%s and uid=%s", (ctime, g.id)) if data: return render_template('push.html', err="您今天已经上传过了") row = insert(sql, (g.id, total_num, ctime)) return render_template('push.html', err="上传成功!")
def upload(): if request.method == "GET": return render_template("upload.html") file_obj = request.files.get("code") file_name = file_obj.filename if not file_name.endswith(".zip"): return "请上传zip格式的压缩文件" target_path = os.path.join("file", str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream, target_path) try: total_num = 0 for base_dir, floder_list, file_list in os.walk(target_path): for filename in file_list: if not filename.endswith(".py"): continue full_path = os.path.join(base_dir, filename) each_num = 0 with open(full_path, "rb") as f: for line in f: line = line.strip() if not line or not line.startswith(b"#"): each_num += 1 continue total_num += each_num except Exception as e: return e date = datetime.date.today() sql = "SELECT id FROM code WHERE date=%s and user_id=%s" params = (date, session["userinfo"]["id"]) if helper.fetchone(sql, params): return "you have uploaded already today" insert_sql = "INSERT INTO code(line,date,user_id) VALUES (%s,%s,%s)" insert_params = (total_num, date, session["userinfo"]["id"]) helper.insert(insert_sql, insert_params) return "upload successfully"
def upload(): if request.method == "GET": return render_template('upload.html') file = request.files.get('code') if not file.filename.endswith('.zip'): return '请上传压缩文件' import shutil target_path = os.path.join('files', str(uuid.uuid4())) # 通过open打开压缩文件, 读取内容进行解压 shutil._unpack_zipfile(file.stream, target_path) # 遍历目录下的所有文件 total_num = 0 for base_path, folder_name, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith('#'): continue file_num += 1 total_num += file_name import datetime ctime = datetime.date.today() # 获取今天时间 mes = helper.fetch_one('select * from Ncode where ctime=%s and user_id=%s', (ctime, session['user_info']['id'])) if mes: return '震惊,今天已经上传过了' helper.insert_m( 'insert into Ncode(number, ctime, user_id) values (%s, %s, %s)', (total_num, ctime, session['user_info']['id'])) return '上传成功'
def uploads(): if request.method == "GET": return render_template("uploads.html") from werkzeug.datastructures import FileStorage file_obj = request.files.get('code') # 1. 检查上传文件后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) # 切开是一个列表 ['aa', 'txt'] if len(name_ext) != 2: # 没有后缀 return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" # """ # # 2. 接收用户上传文件,并写入到服务器本地. # file_path = os.path.join("files",file_obj.filename) # # 从file_obj.stream中读取内容,写入到文件 # file_obj.save(file_path) # # # 3. 解压zip文件 # import shutil # # 通过open打开压缩文件,读取内容再进行解压。 # shutil._unpack_zipfile(file_path,'xsadfasdfasdf') # """ # 2+3, 接收用户上传文件,并解压到指定目录 target_path = os.path.join('upfile', str(uuid.uuid4( ))) # files\91b25a49-fdc1-4059-8022-10b1e96ad218 使用uuid是为了防止上传文件重复 shutil._unpack_zipfile(file_obj.stream, target_path) # aa = os.walk(r"C:\Users\86173\Desktop\22\2\项目配置") # for base_path, folder_list, file_list in aa: # print(base_path) # print(folder_list) # print(file_list) # # os.walk - - 是你所要遍历的目录的地址, 返回的是一个三元组(root, dirs, files)。 # # base_path # 所指的是当前正在遍历的这个文件夹的本身的地址 # folder_list # 是一个 # list ,内容是该文件夹中所有的目录的名字(不包括子目录) # file_list # 同样是 # list, 内容是该文件夹中所有的文件(不包括子目录) # 4. 遍历某目录下的所有文件 统计代码行数数 # for item in os.listdir(target_path): # print(item) total_num = 0 for base_path, folder_list, file_list in os.walk(target_path): print(base_path, "111") print(folder_list, "222") print(file_list, "333") for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) print(file_ext, "22222222") if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num print(total_num, "总数哈哈哈") import datetime ctime = datetime.date.today() print(total_num, ctime, session['user_info']['id']) obj = Mysqls() data = obj.get_one("select id from record where ctime=%s and user_id=%s", (ctime, session['user_info']['id'])) if data: return "今天已经上传" obj.get_mode("insert into record(line,ctime,user_id)values(%s,%s,%s)", (total_num, ctime, session['user_info']['id'])) return "上传成功了"
def upload(): if request.method == "GET": return render_template("upload.html") file_obj = request.files.get("code") print(file_obj.filename) # 上传的文件名 print(file_obj.stream) # 上传的文件内容 # 0.判断今日是否上传过 ctime = datetime.date.today() # 现在的时间 c_obj = helper.fetch_all( 'select create_date from count_code where account_id = %s', (session.get('user_info').get('id'))) for item in c_obj: lib_time = item.get("create_date") if lib_time == ctime: return render_template("upload.html", msg='今日已上传过文件') # 1.检查上传文件后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) if len(name_ext) != 2: return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" """ # 2. 接受用户上传文件,并写入到本地服务器 file_path = os.path.join("statistical_code/media", file_obj.filename) # statistical_code/media/filename print(file_path) file_obj.save(file_path) # 上传的文件保存到path拼接的路径中 # 3. 解压zip文件 shutil._unpack_zipfile(file_path, 'aaa') """ # 2+3, 接受用户上传文件,并解压到指定目录 target_path = os.path.join("statistical_code/media", str(uuid.uuid4())) shutil._unpack_zipfile(file_obj, target_path) # 4.遍历某目录下的所有文件 count = 0 for base_path, folder_list, file_list in os.walk( target_path): # 路径, 文件夹, 文件 for file_name in file_list: file_path = os.path.join(base_path, file_name) if not file_path.endswith('py'): # 不是py文件 continue file_num = 0 with open(file_path, "rb") as f: for line in f: line = line.strip() if not line: # 是空行 continue if line.startswith(b'#'): # 是注释 continue file_num += 1 count += file_num print(file_num, file_path) print(count) # 5.数据保存入数据库 account_id = session.get("user_info").get("id") print(account_id) helper.insert( 'insert into count_code(account_id,create_date,line) ' 'values(%s,%s,%s)', (account_id, ctime, count)) return render_template("upload.html", msg='上传成功共计%s行代码' % count)
def upload(): title = {'title': '代码上传'} msg = '' if request.method == 'GET': return render_template('upload.html', title=title) file_obj = request.files.get( 'code') # <FileStorage: '' ('application/octet-stream')>,把上传的东西方内存了 # print(file_obj.filename) # 上传的文件名(带扩展名) # print(file_obj.stream) # 文件的内容被封装到对象中 # 1.检查上传文件的后缀名 filename_ext = file_obj.filename.rsplit('.', maxsplit=1) # 元组 if len(filename_ext) != 2: msg = '请上传压缩文件!' return render_template('upload.html', msg=msg, title=title) if filename_ext[1] != 'zip': msg = '请上传后缀名为zip的文件' return render_template('upload.html', msg=msg, title=title) # 2.接受用户上传的文件并写入到服务器本地 file_path = os.path.join('files', file_obj.filename) file_obj.save(file_path) # save的本质是:从file_obj.stream中读取内容写入到文件 # 3.解压zip文件 import shutil target_path = os.path.join('files', str(uuid.uuid4())) # 允许上传的文件名相同 # print(target_path)#files/549fb0e2-924c-460d-a993-935fcc8e3274 # 通过open打开i压缩文件,读取内容再进行解压 shutil._unpack_zipfile(file_path, target_path) # 2和3步合并,接受用户上传的文件,并解压至指定目录 # import shutil # shutil._unpack_zipfile(file_obj.stream, r'/home/thanlon/PycharmProjects/code_count/files') # 4. 遍历目录下的所有文件 # for item in os.listdir(target_path): # print(item) # for item in os.walk(target_path): # # 每一个item是一个元组,每一个元组有三个元素,分别是当前路径、当前路径下所有文件夹、当前路径下的所有文件 # print(item) # ('files/79d81a3d-455f-4124-ba24-7d7b8a990c4a/keymaps', [], ['Default Proper Redo.xml']) sum_num = 0 for base_path, folder_list, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) # print(file_path) # files/b39a2b87-69b3-4094-942a-58103e70b8a6/options/databaseDrivers.xml file_ext = file_path.rsplit('.', 1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 # print(file_num, file_path) # 每一个文件行数 sum_num += file_num # print(sum_num) # 获取当前时间 import datetime # ctime = datetime.datetime.now() ctime = datetime.date.today() # 当前日期 # print(sum_num, ctime, session['user_info']['id']) ''' 插入数据之前需要查询今天是否已经提交 ''' sql = 'select id from record where ctime = %s and user_id = %s' args = (ctime, session['user_info']['id']) data = helper.fetchone(sql, args) if data: return '今天的代码已经上传了!' sql = 'insert record(line,ctime,user_id) values(%s,%s,%s)' args = (sum_num, ctime, session['user_info']['id']) helper.insert(sql, args) return '上传成功!'
def upload(): if request.method == "GET": return render_template('upload.html') file_obj = request.files.get("file") file_name = file_obj.filename file_li = file_name.rsplit(".", maxsplit=1) if len(file_li) != 2: error = "请上传带后缀名的文件" elif file_li[1] != "zip": return "请上传文件类型是zip的文件" # file_path =os.path.join(r"C:\Users\Administrator\Desktop\a1",file_name) # file_obj.save(file_path) """ # 2. 接收用户上传文件,并写入到服务器本地. file_path = os.path.join("files",file_obj.filename) # 从file_obj.stream中读取内容,写入到文件 file_obj.save(file_path) # 3. 解压zip文件 import shutil # 通过open打开压缩文件,读取内容再进行解压。 shutil._unpack_zipfile(file_path,'xsadfasdfasdf') """ # 2+3, 接收用户上传文件,并解压到指定目录 import shutil target_path = os.path.join('files', str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream, target_path) # 4. 遍历某目录下的所有文件 # for item in os.listdir(target_path): # print(item) total_num = 0 for base_path, folder_list, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num # 获取当前时间 import datetime date = datetime.date.today() print(total_num, date, session['user']['uid']) data = helper.fetch_one( "select id from record where date=%s and user_id=%s", (date, session['user']['uid'])) if data: return "今天已经上传" print(session['user']['uid'], type(session['user']['uid'])) helper.insert("insert into record(length,date,user_id)values(%s,%s,%s)", (total_num, date, session['user']['uid'])) return "上传成功"
def upload(): if request.method=="GET": return render_template("upload.html") file_obj=request.files.get('code') #1.检查上传文件的后缀名 name_ext=file_obj.filename.rsplit('.',maxsplit=1) if len(name_ext) != 2: return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" #2.接收用户上传文件 获取上传文件并写入到服务器本地 # file_path=os.path.join("files",file_obj.filename) # file_obj.save(file_path) #3.解压zip文件 #2+3接收文件并解压到指定目录 target_path = os.path.join('files',str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream,target_path) #4.遍历某个目录下的所有文件 total_num=0 for base_path,folder_list,file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path,file_name) file_ext=file_path.rsplit('.',maxsplit=1) if len(file_ext) !=2: continue if file_ext[1]!='py': continue file_num=0 with open(file_path,'rb') as f: for line in f: line=line.strip() if not line: continue if line.startswith(b'#'): continue file_num+=1 total_num+=file_num # print(total_num) #4.5 获取当前时间 import datetime ctime=datetime.datetime.now() #4.6 查询是否上传 # conn = pymysql.connect(host='127.0.0.1', user='******', password='', charset='utf8', database='s9day118') # cursor = conn.cursor(cursor=pymysql.cursors.dictcursor) # cursor.execute('select id from record where ctime=%s and user_id=%s', # (ctime, session['user_info']['id'])) # date=cursor.fetchone() # cursor.close() # conn.close() date=helper.featch_one('select id from record where ctime=%s and user_id=%s',(ctime, session['user_info']['id'])) if date: return "今天代码已上传" #5.上传代码信息 # conn = pymysql.connect(host='127.0.0.1', user='******', password='', charset='utf8', database='s9day118') # cursor = conn.cursor(cursor=pymysql.cursors.dictcursor) # cursor.execute('insert into record(line,ctime,user_id) values (%s,%s,%s)', (total_num,ctime,session['user_info']['id'])) # conn.commit() # cursor.close() # conn.close() helper.insert('insert into record(line,ctime,user_id) values (%s,%s,%s)', (total_num,ctime,session['user_info']['id'])) return "上传成功"
def update_event(self, inp=-1): self.set_output_val(0, shutil._unpack_zipfile(self.input(0), self.input(1)))
def upload(): if request.method == 'GET': return render_template('upload.html') file_obj = request.files.get('code') print(file_obj) # 1.检查上传文件的后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) print(name_ext) if len(name_ext) != 2: return '请上传zip压缩文件' if name_ext[1] != 'zip': return '请上传zip压缩文件' """ # 2.设置用户最大限制能传多少M文件 设置在settings # 2.5获取上传的文件 并写入到本地服务器 file_path = os.path.join("files", file_obj.filename) # 从file_obj.stream中读取内容,写入到文件 file_obj.save(file_path) # 3. 解压zip文件 import shutil # 通过open打开压缩文件,读取内容再进行解压 shutil._unpack_zipfile(file_path,'asdsada') """ # 2+3,接受用户上传文件,并解压到指定目录 import shutil target_path = os.path.join('files', str(uuid.uuid4())) # file_obj.stream 拿到里面的内容 shutil._unpack_zipfile(file_obj.stream, target_path) # 4 遍历所有文件 total_num = 0 # 所有代码的行数 for base_path, folder, file_list in os.walk(target_path): for file_name in file_list: # 路径和文件名拼接 file_path = os.path.join(base_path, file_name) # print(file_path) file_ext = file_path.rsplit('.', maxsplit=1) # print(file_ext) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 # 一个文件中的代码行数 with open(file_path, 'rb') as f: for line in f: line = line.strip() # 空行1 if not line: continue if line.startswith(b'#'): # 注释 continue file_num += 1 print(file_num, file_path) total_num += file_num print(total_num) # 获取当前时间 import datetime ctime = datetime.date.today() # 查询数据库 import pymysql # conn = pymysql.Connect(host='127.0.0.1',user='******',password='******',database='day118',charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute('select id from record where ctime=%s and user_id=%s',(ctime,session['user_info']['id'])) # data = cursor.fetchone() # cursor.close() # conn.close() data = helper.fetch_one( 'select id from record where ctime=%s and user_id=%s', (ctime, session['user_info']['id'])) if data: return '今天已上传' # 写入数据库 import pymysql # conn = pymysql.Connect(host='127.0.0.1', user='******', password='******', database='day118', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute('insert into record(line,ctime,user_id)value (%s,%s,%s)',(total_num,ctime,session['user_info']['id'])) # conn.commit() # cursor.close() # conn.close() helper.insert('insert into record(line,ctime,user_id)value (%s,%s,%s)', (total_num, ctime, session['user_info']['id'])) return '上传成功'
def jishu(request): user = request.session.get('user') if request.method == 'GET': if user: return render(request, 'jishu.html') else: return redirect('/login/') else: file_obj = request.FILES.get('file') #file 的四个对象 read (内容),size(大小) content_type(查看属性) # print(file_obj.name) # print(file_obj.read) # print(file_obj.content_type) c, v = file_obj.name.rsplit('.', maxsplit=1) if not v or v != 'zip': return HttpResponse('请上传正确格式的文件') import shutil import uuid import os # print(os.path) target_path = os.path.join('files', str(uuid.uuid4())) # target_path = os.path.join(MEDIA_PATH,str(uuid.uuid4())) # 接收用户上传文件,并解压到指定目录 shutil._unpack_zipfile(file_obj, target_path) # with open(target_path,'wb') as f: # for info in file_obj.chunks():#chunks是生成器 可以一点点的读数据 防止文件过大 # f.write(info) # f.close() # print(os.walk(target_path))#循环列出该文件夹下所有的文件 totle_num = 0 for base_path, floder_path, filter_list in os.walk(target_path): for file_name in filter_list: file_path = os.path.join(base_path, file_name) try: c, v = file_path.rsplit('.', maxsplit=1) except: continue if not v or v != 'py': continue with open(file_path, 'rb') as f1: num = 0 for info in f1: info.strip() if not info: continue if info.startswith(b'#'): #以B开头的注释 continue else: num += 1 totle_num += num import datetime date = str(datetime.datetime.today().date()) num = str(totle_num) name = request.session.get('user') print(name, date, num) try: Userinfo.objects.update_or_create(name=name, date=date, num=num) except: return HttpResponse('你今天已经上传过了') return HttpResponse('上传成功')
import hashlib def md5(arg): hash = hashlib.md5('ghjkl;') hash.update(bytes(arg, encoding='utf-8')) ret = hash.hexdigest() return hash.hexdigest() #解压文件 import shutil #通过open打开压缩文件,读取内容在进行解压(可二进制,str) shutil._unpack_zipfile(r'xx.zip')
def uplode(): if request.method == 'GET': return render_template('uplode.html') file_obj = request.files.get('code') # print(type(file_obj)) # print(file_obj.filename) # print(file_obj.stream) # 1 上传压缩文件 new_tuple_name = file_obj.filename.rsplit('.', maxsplit=1) # print('new_tuple_name', new_tuple_name) ['新建文本文档', 'txt'] if len(new_tuple_name) != 2: return '请上传zip文件' if new_tuple_name[1] != 'zip': return '请上传zip文件' ''' # 2 接收并处理 # 获取路径并保存在本地服务器 file_path = os.path.join('file', file_obj.filename) file_obj.save(file_path) # 3 解压zip文件 shutil._unpack_zipfile(file_path, r'D:/untitled/基础知识/day117/homework/file') ''' # 2 读取压缩文件的内容file_obj.stream,并解压上传 unpack_path = os.path.join('file', str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream, unpack_path) # 3 遍历文件夹的内容 # ('file\\165ce7b0-e830-4dec-b419-e3ab80800c00', ['s5alipay', '__MACOSX'], []) total_num = 0 for base_path, file_folder_list, file_list in os.walk(unpack_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) # 单个文件名的具体路径 file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num # 4 写入数据库 ctime = datetime.date.today() print(total_num, ctime, session['user_info']['id']) ''' conn = pymysql.connect(host='127.0.0.1', user='******', password='******', database='flaskhome', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id from Coderecord where datrtime=%s and user_id=%s",(ctime,session['user_info']['id'])) data = cursor.fetchone() cursor.close() conn.close() ''' data = sqlhelper.fetch_one("select id from Coderecord where datrtime=%s and user_id=%s", (ctime, session['user_info']['id'])) if data: return "今天已经上传" # conn = pymysql.connect(host='127.0.0.1', user='******', password='******', database='flaskhome', charset='utf8') # # cursor = conn.cursor() # 元祖 # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 字典 # cursor.execute("INSERT INTO Coderecord(line,datrtime,user_id) VALUE (%s,%s,%s) ",(total_num, ctime, session['user_info']['id'])) # conn.commit() # cursor.close() # conn.close() sqlhelper.insert("INSERT INTO Coderecord(line,datrtime,user_id) VALUE (%s,%s,%s) ", (total_num, ctime, session['user_info']['id'])) return render_template('uplode.html')
def upload(): if request.method == "GET": return render_template('upload.html') from werkzeug.datastructures import FileStorage file_obj = request.files.get('code') # 1. 检查上传文件后缀名 name_ext = file_obj.filename.rsplit('.', maxsplit=1) if len(name_ext) != 2: return "请上传zip压缩文件" if name_ext[1] != 'zip': return "请上传zip压缩文件" """ # 2. 接收用户上传文件,并写入到服务器本地. file_path = os.path.join("files",file_obj.filename) # 从file_obj.stream中读取内容,写入到文件 file_obj.save(file_path) # 3. 解压zip文件 import shutil # 通过open打开压缩文件,读取内容再进行解压。 shutil._unpack_zipfile(file_path,'xsadfasdfasdf') """ # 2+3, 接收用户上传文件,并解压到指定目录 import shutil target_path = os.path.join('files', str(uuid.uuid4())) shutil._unpack_zipfile(file_obj.stream, target_path) # 4. 遍历某目录下的所有文件 # for item in os.listdir(target_path): # print(item) total_num = 0 for base_path, folder_list, file_list in os.walk(target_path): for file_name in file_list: file_path = os.path.join(base_path, file_name) file_ext = file_path.rsplit('.', maxsplit=1) if len(file_ext) != 2: continue if file_ext[1] != 'py': continue file_num = 0 with open(file_path, 'rb') as f: for line in f: line = line.strip() if not line: continue if line.startswith(b'#'): continue file_num += 1 total_num += file_num # 获取当前时间 import datetime ctime = datetime.date.today() print(total_num, ctime, session['user_info']['id']) # import pymysql # conn = pymysql.Connect(host='127.0.0.1', user='******', password='******', database='s9day118', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute("select id from record where ctime=%s and user_id=%s",(ctime,session['user_info']['id'])) # data = cursor.fetchone() # cursor.close() # conn.close() data = helper.fetch_one( "select id from record where ctime=%s and user_id=%s", (ctime, session['user_info']['id'])) if data: return "今天已经上传" # import pymysql # conn = pymysql.Connect(host='127.0.0.1', user='******', password='******', database='s9day118', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor.execute("insert into record(line,ctime,user_id)values(%s,%s,%s)",(total_num,ctime,session['user_info']['id'])) # conn.commit() # cursor.close() # conn.close() helper.insert("insert into record(line,ctime,user_id)values(%s,%s,%s)", (total_num, ctime, session['user_info']['id'])) return "上传成功"
def jieya(): import shutil #通过open打开压缩文件,读取内容在进行解压(可二进制,str) shutil._unpack_zipfile(r'xx.zip')
# 1. 加密 # import hashlib # hash = hashlib.md5(b"sdf1123df") # # hash.update(bytes('123456',encoding='utf-8')) # # ret = hash.hexdigest() # print(ret) import shutil shutil._unpack_zipfile( r"/Users/zhangyifei/PycharmProjects/CodingStatistic/files/year_code-master.zip", r"/Users/zhangyifei/PycharmProjects/CodingStatistic/files")
# print(ret) # 2. 数据库操作 # import pymysql # # conn = pymysql.Connect(host='127.0.0.1',user='******',password='******',database='s9day118',charset='utf8') # # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # # # 不要这么用 # # sql = "select * from userinfo where user='******' and pwd ='%s'" %("xiao ' or 1=1 -- ","47f5abdd7f4083f0cc5c94d587fa3ca4") # # # cursor.execute("select * from userinfo where user=%s and pwd =%s",("xiaoqiang","47f5abdd7f4083f0cc5c94d587fa3ca4")) # cursor.execute("select * from userinfo where user=%(us)s and pwd =%(pw)s",{"us":"xiaoqiang","pw":"47f5abdd7f4083f0cc5c94d587fa3ca4"}) # # # data = cursor.fetchall() # data = cursor.fetchone() # # cursor.close() # conn.close() # # print(data) # 3. 解压文件 import shutil shutil._unpack_zipfile( r"E:\wupeiqi\s9\homework-晓强\homework\files\luffy-vue简单示例(一).zip", r"E:\wupeiqi\s9\homework-晓强\homework\xxx")
# ret = hash.hexdigest() # print(ret) ''' 连接数据库 ''' # import pymysql # # conn = pymysql.Connect(host='localhost', user='******', password='******', # database='codecount') # 如果中文不能显示,设置charset = 'utf8' # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置拿到的是字典,不设置是元组 # # 不要自己去拼接 # # sql = "select *from userinfo where user = '******' and pwd = '%s'" % ( # # "thanl' or 1=1-- ", '63d7d0d52449193ba1f1321cd8b89a62') # # # cursor.execute('select *from userinfo where user = %s and pwd = %s', # # ("thanlon", '63d7d0d52449193ba1f1321cd8b89a62')) # cursor.execute('select *from userinfo where user = %(us)s and pwd = %(pw)s', # {'us': "thanlon", 'pw': '63d7d0d52449193ba1f1321cd8b89a62'}) # # data = cursor.fetchall() # data = cursor.fetchone() # 匹配成功的第一条数据,如果失败,返回None # print(data) # cursor.close() # conn.close() # 解压文件 import shutil shutil._unpack_zipfile( r'/home/thanlon/PycharmProjects/code_count/files/flask.zip', '/home/thanlon/PycharmProjects/code_count/files/')