I've been studying this example project. Very concise and to the point, and a pleasant surprise, too: a Save File Dialog (a standard desktop File Dialog, opened from Chrome).
The responsible code:
src/html.py
:
@app.post('/download')
def form_post(request: Request, num: int = Form(...), multiply_by_2: bool = Form(False), action: str = Form(...)):
if action == 'convert':
result = spell_number(num, multiply_by_2)
return templates.TemplateResponse('download.html', context={'request': request, 'result': result, 'num': num})
elif action == 'download':
# Requires aiofiles
result = spell_number(num, multiply_by_2)
filepath = save_to_text(result, num)
return FileResponse(filepath, media_type='application/octet-stream', filename='{}.txt'.format(num))
templates/download.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form method="post">
<input type="number" name="num" value="{{ num }}"/>
<input type="checkbox" id="multiply_by_2" name="multiply_by_2" value="True">
<label for="multiply_by_2">Multiply by 2 </label>
<input type="submit" name="action" value="convert">
<input type="submit" name="action" value="download">
</form>
<p>Result: {{ result }}</p>
</body>
</html>
I can't see any hint on a File Dialog in FileResponse
, much less on the Save File Dialog, which pops up. I want the Open File Dialog too, by the way. I tried to research it, without success.
How does it work?
UPD, to make myself clearer.
I'm playing with something like this:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
...
@app.post("/open")
def form_post(
request: Request,
action: str = Form("open"),
):
if action == "open":
root = Tk()
root.withdraw()
# ensure the file dialog pops to the top window
root.wm_attributes('-topmost', 1)
fname = askopenfilename(parent=root)
print(f"Chosen file: {fname}")
return templates.TemplateResponse("open.html", context={"request": request})
elif action == "save":
# Requires aiofiles
return FileResponse(
"templates/legacy/download.html",
media_type="text/html",
filename="download.html",
)
For now, button save
makes use of the system Save File Dialog, while button open
employs tkinter's Open Dialog. It will do, because the whole thing is merely an application with a Web UI. Still, it looks and feels a bit ridiculous.
Is there a way to make the browser serve the Open File Dialg?