Skip to content

Commit

Permalink
examples: update Python examples
Browse files Browse the repository at this point in the history
Aside from moving to the new API, handle the IsADirectoryError case by
using reopen_raw() for directories.

Signed-off-by: Aleksa Sarai <[email protected]>
  • Loading branch information
cyphar committed Jul 18, 2024
1 parent 5dcb75d commit d7c3bd4
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions examples/static_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("/<path:path>")
def get(path):
try:
Expand All @@ -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:
Expand All @@ -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__":
Expand Down

0 comments on commit d7c3bd4

Please sign in to comment.