External Exam Download Resources Web Applications Games Recycle Bin

file mangler

Remember to create a new static folder for script to work:

filemangler.py

from flask import *
import os, sys
app = Flask(__name__)
if not os.path.exists(app.static_folder):
    os.makedirs(app.static_folder)

current_folder = app.static_folder

@app.route("/")
def list_items():
    global current_folder
    hide_back_link = False
    if current_folder == app.static_folder:
        hide_back_link = True
    return render_template("file_operations.html",
                           hide_back_link = hide_back_link,
                           folder = current_folder,
                           contents = get_contents_of(current_folder))

@app.route("/<folder>")
def open(folder):
    global current_folder
    current_folder = os.path.join(current_folder, folder)
    return redirect("/")

@app.route("/[back]")
def back():
    global current_folder
    current_folder = os.path.dirname(current_folder)
    return redirect("/")

def get_contents_of(path):
    fileList = []
    folderList = []
    global current_folder
    for item in os.scandir(path):
        #remove OSX files that start with a '.':
        if not item.name.startswith('.') and item.is_file():
            relative_url = os.path.relpath(current_folder, app.static_folder)
            relative_link = os.path.join('static', relative_url, item.name)
            fileList.append([item.name, relative_link])
        else:
            folderList.append(item.name)
    return [fileList, folderList]

@app.route("/make_dir", methods=["POST"])
def make_dir():
    global current_folder
    new_dir = os.path.join(current_folder, request.form["dir"])
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)
    return redirect("/")

@app.route("/delete", methods=["POST"])
def delete():
    global current_folder
    file_to_delete = os.path.join(current_folder, request.form["file_to_delete"])
    os.remove(file_to_delete)
    return redirect("/")

@app.route('/favicon.ico') 
def favicon():
    return ""
    
app.run(debug=True)

templates\file_operations.html

<h1>{{folder}}</h1>
<h2>files:</h2>
<form action="/delete" method="post">
{% for file in contents[0] %}
  <a href="{{file[1]}}">{{file[0]}}</a>
  <button type="submit" name="file_to_delete" value="{{file[0]}}">delete</button><br>
{% endfor %}
</form>

<h2>folders:</h2>

{% if hide_back_link == false %}
  <a href="/[back]">[back]</a><br>
{% endif %}

{% for folder in contents[1] %}
  <a href="/{{folder}}">{{folder}}</a><br>
{% endfor %}

<h2>make directory:</h2>
<form action="/make_dir" method="post">
<input type="text" name="dir">
<input type="submit">
</form>