乐趣区

关于flask:flask-web-实现文件上传-下载-浏览-编辑

性能展现

代码展现

app.yp

from flask import Flask, request, render_template, redirect, url_for, make_response ,escape, session, flash, g, current_app, abort, jsonify, send_file
import requests
from werkzeug.utils import secure_filename
import os,time, platform
from flask_wtf import Form
from wtforms import TextField
from shell import os_scrpict, harbor
import sqlite3
from pathlib import Path
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
#app.pyapp.secret_key = 'development key'
app.config['UPLOAD_FOLDER'] = 'upload/'

filepath = Path('upload/')


@app.route('/upload')
def upload_file():
   return render_template('dir_view.html')



@app.route('/uploader', methods = ['GET', 'POST'])
@app.route('/uploader/<path:filepath>/', methods = ['GET', 'POST'])
def uploader(filepath=' '):
   if request.method == 'POST':
       repath = 'upload/' + filepath + '/'
       print(repath)
       f = request.files['file']
       #f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
       f.save(os.path.join(repath, secure_filename(f.filename)))
       #return 'file uploaded successfully'
       return redirect('/scan/{tfilepath}'.format(tfilepath = filepath))


@app.route('/download/<path:fullname>',)
def download_file(fullname):
    #current_app.logger.debug(fullname)
    print(fullname)
    return send_file(fullname)



@app.route('/look/<path:fullname>',)
def look_file(fullname):
    f = open(fullname, encoding='UTF-8')
    resp = make_response(f.read())
    #resp = make_response(open(fullname, encoding='UTF-8').read())
    resp.headers["Content-type"] = "application/json;charset=UTF-8"
    # f = open(fullname, "r+",encoding='UTF-8',newline="\n")
    # str = f.read()
    # fullname1 = str(fullname).replace('\\', '/')
    # with open(fullname, "r+",encoding='UTF-8',newline="\n") as f:  # 默认模式为‘r',只读模式
    #     contents = f.read()
    f.close()
    return resp




@app.route('/scan/')
@app.route('/scan/<path:ortherpath>/',)
def index(ortherpath=''):
    file_ele_list = list()
    dir_ele_list = list()
    #for f in (Path('upload/'+ ortherpath).iterdir()):
    for f in (Path('upload') / Path(ortherpath)).iterdir():
    #for f in os_scrpict.allfile('upload/'):
        if f.is_file():
            fullname = str(f).replace('\\', '/')
            file_ele_list.append({'is_dir': 0, 'filesize': os.path.getsize(f) / 1000,
                                  'last_modify_time': time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(fullname))),
                                  'look_url': url_for('look_file', fullname=fullname), 'download_url': url_for('download_file', fullname = fullname), 'fullname': fullname})
        if f.is_dir():
            fullname = str(f).replace('\\', '/')
            dirname = fullname.split('/')
            dir_ele_list.append({'is_dir': 1, 'filesize': 0,
                                 'last_modify_time': time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(fullname))), 'look_url': url_for('look_file', fullname = dirname[1]), 'download_url': url_for('index', ortherpath = dirname[1]), 'fullname': fullname})
            #print(dirname[1],"########",dir_ele_list)
        #print(fullname,"fullname####",fullname[1:])
    print(dir_ele_list + file_ele_list)
    repath = request.path.split('scan')
    print(request.path,"#############request.path##########",repath[1])
    if 'look' in request.path:
        look_file1 = request.path.split('look/')
        return render_template('dir_view.html', ele_list=dir_ele_list + file_ele_list,path1 = {"path1": repath[1]},conflook = {"conflook": look_file(look_file1[1])})
    else:

        return render_template('dir_view.html', ele_list=dir_ele_list + file_ele_list, path1={"path1": repath[1]}, conflook = {"conflook": "hello kugou"})


@app.route('/get_configfile/<path:configname>',)
def get_configfile(configname):
    print(configname)
    f = open(configname, "r+",encoding='UTF-8',newline="\n")
    str = f.read()
    f.close()
    return render_template('get_configfile.html', conflook = {"conflook": str,"configname": configname})


@app.route('/edit_configfile/<path:configname>/', methods = ['GET', 'POST'])
def edit_configfile(configname):
    if request.method == 'POST':
        fileconfig = request.form.get('conftext')
        print(configname)
        print(fileconfig)
        f = open(configname, 'w', encoding='utf8')
        # 写入文件内容
        f.write(fileconfig)
        f.close()

    return redirect('/scan/')


if __name__ == '__main__':
    app.run()
    #app.run(host="172.16.117.33",port=5888)

dir_view.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="container" style="position: absolute;left: -2%;width: 1590px;height: 850px;margin-left: 95px;display:block;overflow-y:auto;">

    <div style="width: 590px;height: 80px;">
        <form action="http://localhost:5000/uploader{{path1.path1}}" method="POST" enctype="multipart/form-data">
            <input type="file" name="file" accept="*.*"/>
            <input type="submit"/>
        </form>
    </div>
    <div style="float: left; width:938px;height:70px"><a> dir_path : {{path1.path1}} </a></div>



    <table class="table table-condensed" id="table1">
        <thead>
        <tr>
            <th> 名称 </th>
            <th> 最初批改工夫 </th>
            <th> 文件大小 </th>
            <th> 下载文件 </th>
            <th> 操作 </th>
        </tr>
        </thead>
        <tbody>
        {% for ele in ele_list %}
            {% if ele.is_dir %}
                <tr class="warning">
                    <td><a> 目录 {{ele.fullname}}</a></td>
                    <td>{{ele.last_modify_time}}</td>
                    <td>{{ele.filesize}} M</td>
                    <td><a href="{{ele.download_url}}"> 进入 {{ele.fullname}}</a></td>
                    <td><a  href="{{ele.download_url}}"> 关上目录 </a></td>
                    {% else %}
                <tr class="success">
                <td><a href="{{ele.look_url}}"> {{ele.fullname}}</a></td>
                <td>{{ele.last_modify_time}}</td>
                <td>{{ele.filesize}} Kb</td>
                <td><a href="{{ele.download_url}}" download={{ele.fullname}}> 下载 {{ele.fullname}}</a></td>
                <td>
                <a  href="/get_configfile/{{ele.fullname}}"><font size="2" face="arial" color="blue"> <i class="fa fa-pencil" aria-hidden="true"></i> 编辑 </font></a>
                </td>
            {% endif %}

        {#            <td><a href="{{ ele.look_url}}" > 预览 {{ele.fullname}}</a></td>#}
        {#            <td>{{ ele.last_modify_time}}</td>#}
        {#            <td>{{ ele.filesize}} M</td>#}
        {#            <td><a href="{{ ele.download_url}}" download={{ele.fullname}}> 下载 {{ele.fullname}}</a></td>#}
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
</body>
</html>

get_configfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>Nginx_config</h2>
    <form method="POST" action="/edit_configfile/{{conflook.configname}}">
        <div style="position: absolute;left: 4%;width: 690px;height: 850px;">
            <p> nginx_config-text:<textarea rows="35" cols="120" name="conftext"> {{conflook.conflook}} </textarea>
            </p>
        </div>
        <div style="position: absolute;top: 800px;left: 77%;width: 150px;height: 150px;"
        ">
        <input type="submit" value="提交"/>
        <a href="/scan/"><font size="2" face="arial" color="blue" class="btn btn-default"> <i class="fa fa-pencil"
                                                                                              aria-hidden="true"></i>
            home </font></a>
        </div>
    </form>
</body>
</html>

  • 款式 模板 写的有点糙,就不给你们了
退出移动版