FastAPI/Starlette, Web UI: Save File Dialog, Open File Dialog

  fastapi, python, starlette

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&nbsp;</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?

Source: Python Questions

LEAVE A COMMENT