# -*- coding: utf-8 -*- import os from flask import Flask, request, url_for, send_from_directory, flash, get_flashed_messages, render_template from werkzeug.utils import secure_filename import difflib import sys ALLOWED_EXTENSIONS = set(['properties', 'conf', 'py', 'txt']) app = Flask(__name__) app.config['SECRET_KEY'] = '123456' app.config['UPLOAD_FOLDER'] = os.getcwd() app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 files = [] def readfile(filename): try: fileHandle=open(filename, encoding='gb18030',errors='ignore') text=fileHandle.read().splitlines() fileHandle.close() return text except IOError as error: print("Read file Error:"+str(error)) sys.exit() def web_diff(file1,file2): text1_lines = readfile(os.getcwd()+'\'+ file1) text2_lines = readfile(os.getcwd()+'\'+ file2) d = difflib.HtmlDiff() result = d.make_file(text1_lines, text2_lines, context=True) old_str='charset=ISO-8859-1' new_str='charset=UTF-8' with open('templates/result.html', 'w', encoding='utf-8') as f: f.writelines(result.replace(old_str,new_str)) def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) @app.route('/upload/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': for file in request.files.getlist('file'): if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file = str(file) files.append(file.split()[1]) flash('文件上传成功') if request.form.get('diff'): web_diff(files[0].replace("'",""),files[1].replace("'","")) return render_template('result.html') return render_template('upload.html') if __name__ == '__main__': app.run()
templates/upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload File</title> </head> <body> <h1>文件上传</h1> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=file name=file> <input type=submit value=上传> </form> <form method=post> <input type=submit value=对比> <input name=diff type=hidden value=0> </form> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} </body> </html>