Skip to content

Instantly share code, notes, and snippets.

@KillerGoldFisch
Last active January 20, 2021 14:18
Show Gist options
  • Save KillerGoldFisch/1bd60139ffa1c309e5ab to your computer and use it in GitHub Desktop.
Save KillerGoldFisch/1bd60139ffa1c309e5ab to your computer and use it in GitHub Desktop.
Flask server for static directorys with filebrowser
#!/usr/bin/python
#
# Flask server, woo!
#
from flask import Flask, abort, send_file, render_template_string
import os
# Setup Flask app.
app = Flask(__name__)
app.debug = True
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
BASE_DIR = os.path.abspath(".")
# Joining the base and the requested path
abs_path = os.path.join(BASE_DIR, req_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
return send_file(abs_path)
# Show directory contents
files = os.listdir(abs_path)
files = [os.path.join(req_path, f).replace('\\', '/') for f in files]
return render_template_string("""
<ul>
{% for file in files %}
<li><a href="/{{ file }}">{{ file }}</a></li>
{% endfor %}
</ul>
""", files=files)
if __name__ == '__main__':
app.run()
@KillerGoldFisch
Copy link
Author

Hi,

danke für das Feedback! Ich hab den Fehler gefunden und gefixt.

Das Problem war in <li><a href="{{ file }}">{{ file }}</a></li>. Dabei wurde eine relative href erzeugt.
Ich hab es jetzt durch <li><a href="/{{ file }}">{{ file }}</a></li> ersetzt. Also ein absoluter Verweis.

Grüße,
Kevin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment