项目结构
from flask import Flask, render_template, request, redirect, url_for
import os
app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
FILE_DIR = os.path.join(BASE_DIR, 'testfile')
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'create' in request.form:
dirname = request.form.get('dirname')
os.mkdir(os.path.join(FILE_DIR, dirname))
elif 'delete' in request.form:
dirname = request.form.get('dirname')
os.rmdir(os.path.join(FILE_DIR, dirname))
return redirect(url_for('index'))
directories = os.listdir(FILE_DIR)
return render_template('index.html', directories=directories)
if __name__ == '__main__':
if not os.path.isdir('testfile'):
os.makedirs('testfile')
app.run(debug=True)
templates / index.html
<!DOCTYPE html>
<html>
<head>
<title>File Manager</title>
</head>
<body>
<h1>File Manager</h1>
<form method="POST">
<input type="text" name="dirname" placeholder="Directory Name">
<input type="submit" name="create" value="Create Directory">
<input type="submit" name="delete" value="Delete Directory">
</form>
<ul>
{% for directory in directories %}
<li>{{ directory }}</li>
{% endfor %}
</ul>
</body>
</html>
效果图