zoukankan      html  css  js  c++  java
  • Python ---- 基于Flask框架做出简易网页端上传两文件并对比出不同内容

    # -*- 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>
  • 相关阅读:
    模型驱动架构探索之游戏引擎设计 (二)开始建模
    模型驱动架构探索之游戏引擎设计 (二)粒度统一
    模型驱动架构探索之游戏引擎设计 (一)
    模型驱动架构探索之游戏引擎设计 (序)
    时隔几年,再写传统的简单问题算法,又有何不同?
    【自学笔记】0基础自学机器学习 (第三天)
    【自学笔记】0基础自学机器学习 (第二天)
    JavaSE-知识点总结
    Java框架之SpringBoot 09-Web构建-yml-模块-注解
    Java框架之SpringSecurity 08-权限系统
  • 原文地址:https://www.cnblogs.com/k-free-bolg/p/13085896.html
Copyright © 2011-2022 走看看