diff --git a/examples/static_web.py b/examples/static_web.py index 88f8bf6..dc0e260 100755 --- a/examples/static_web.py +++ b/examples/static_web.py @@ -22,14 +22,33 @@ import os import sys +import stat import errno import flask +import flask.json + sys.path.append(os.path.dirname(__file__) + "/../contrib/bindings/python") import pathrs app = flask.Flask(__name__) +def json_dentry(dentry): + st = dentry.stat(follow_symlinks=False) + return { + "ino": st.st_ino, + "mode": stat.S_IMODE(st.st_mode), + "type": { + stat.S_IFREG: "regular file", + stat.S_IFDIR: "directory", + stat.S_IFLNK: "symlink", + stat.S_IFBLK: "block device", + stat.S_IFCHR: "character device", + stat.S_IFIFO: "named pipe", + stat.S_IFSOCK: "socket", + }.get(stat.S_IFMT(st.st_mode)), + } + @app.route("/") def get(path): try: @@ -43,10 +62,18 @@ def get(path): # Permission denied => 403 Forbidden. errno.EACCES: 403, }.get(e.errno, 500) - flask.abort(status_code, "Could not resolve path.") + flask.abort(status_code, "Could not resolve path: %s." % (e,)) - f = handle.reopen("rb") - return flask.Response(f, mimetype="application/octet-stream", direct_passthrough=True) + try: + f = handle.reopen("rb") + return flask.Response(f, mimetype="application/octet-stream", direct_passthrough=True) + except IsADirectoryError: + f = handle.reopen_raw(os.O_RDONLY) + with os.scandir(f.fileno()) as s: + return flask.json.jsonify({ + dentry.name: json_dentry(dentry) + for dentry in s + }) def main(root_path=None): if root_path is None: @@ -56,7 +83,7 @@ def main(root_path=None): global root root = pathrs.Root(root_path) - # Now server our dumb HTTP server. + # Now serve our dumb HTTP server. app.run(debug=True, port=8080) if __name__ == "__main__":