Skip to content

Instantly share code, notes, and snippets.

@kemingy
Created July 7, 2018 12:55
Show Gist options
  • Select an option

  • Save kemingy/948064d9637f6669773aefb3cfea946f to your computer and use it in GitHub Desktop.

Select an option

Save kemingy/948064d9637f6669773aefb3cfea946f to your computer and use it in GitHub Desktop.
file browser writen in Python with Flask Blueprint
import os
from flask import Flask, Blueprint, send_file, render_template, abort, jsonify
from time import ctime
SIZES = ['B', 'K', 'M', 'G']
CURRENT_PATH = os.path.abspath(os.path.curdir)
bp = Blueprint(
'file_browser',
__name__,
template_folder=CURRENT_PATH,
)
def size4human(size):
index = 0
while size > 1024:
size /= 1024
index += 1
return '{:.2f}{}'.format(size, SIZES[index])
def get_file_info(files, path):
info = [{
'name': f,
'size': size4human(os.path.getsize(os.path.join(path, f))),
'update_time': ctime(os.path.getmtime(os.path.join(path, f))),
'type': 'file' if os.path.isfile(os.path.join(path, f)) else 'folder',
} for f in files]
return info
@bp.route('/')
def index():
return file_browser('.')
@bp.route('/<path:filepath>')
def file_browser(filepath=None):
path = os.path.join(CURRENT_PATH, filepath)
if os.path.isdir(path):
files = get_file_info(os.listdir(path), path)
return jsonify(files=files)
elif os.path.isfile(path):
if filepath.endswith('.html'):
return render_template(filepath)
return send_file(path, as_attachment=True)
abort(404)
app = Flask(__name__)
app.register_blueprint(bp)
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment