Skip to content

Commit 6fdbddc

Browse files
committed
[New] files: support for format=json to list the contents
1 parent 008b2d7 commit 6fdbddc

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

.editorconfig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[*.py]
2-
indent_style=space
2+
indent_style=tab
33
indent_size=4
44
tab_width=4

src/py/extra/services/files.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,29 @@ def __init__(self, root: Path | None = None):
5050
self.canDelete: Callable[[HTTPRequest, Path], bool] = lambda r, p: True
5151

5252
def renderPath(
53-
self, request: HTTPRequest, path: str, localPath: Path
53+
self,
54+
request: HTTPRequest,
55+
path: str,
56+
localPath: Path,
57+
format: str,
5458
) -> HTTPResponse:
5559
path = path.strip("/")
5660
if localPath.is_dir():
57-
return self.renderDir(request, path, localPath)
61+
match format:
62+
# We support the JSON format to list the contents of a diretory
63+
case "json":
64+
root = os.path.abspath(path)
65+
return request.returns(
66+
[
67+
{
68+
"path": _.relative_to(root),
69+
"type": "directory" if _.is_dir() else "file",
70+
}
71+
for _ in localPath.iterdir()
72+
]
73+
)
74+
case _:
75+
return self.renderDir(request, path, localPath)
5876
else:
5977
return request.respondFile(
6078
localPath, contentType=self.guessContentType(localPath)
@@ -169,13 +187,14 @@ def head(self, request: HTTPRequest, path: str) -> HTTPResponse:
169187
@cors
170188
@on(GET=("/", "/{path:any}"))
171189
def read(self, request: HTTPRequest, path: str = ".") -> HTTPResponse:
190+
format: str = request.param("format", "html")
172191
local_path = self.resolvePath(path)
173192
if not (local_path and self.canRead(request, local_path)):
174193
return request.notAuthorized(f"Not authorized to access path: {path}")
175194
elif not local_path.exists():
176195
return request.notFound()
177196
else:
178-
return self.renderPath(request, path, local_path)
197+
return self.renderPath(request, path, local_path, format=format)
179198

180199
@on(PUT_PATCH="/{path:any}")
181200
def write(self, request: HTTPRequest, path: str = ".") -> HTTPResponse:

0 commit comments

Comments
 (0)