newsmode
search
Меню
arrow_back Назад

Adding a Checkbox & Download Button to a FastAPI-HTML app

auto_awesomeКраткое саммари

Статья описывает, как расширить простое HTML-приложение на FastAPI, добавив чекбокс и кнопку скачивания. Чекбокс позволяет пользователю умножить введённое число на два перед преобразованием в текст, а кнопка скачивания — сохранить результат в файл. Для работы FileResponse необходим пакет aiofiles. Логика маршрута обрабатывает два действия: конвертацию с выводом на страницу и скачивание текстового файла. Весь код доступен в репозитории fastapi-html на GitHub.

Adding a Checkbox & Download Button to a FastAPI-HTML app

Добавляем чекбокс и кнопку скачивания в FastAPI-HTML приложение

[ engineering python til ] · 3 min read

[ engineering python til ] · 3 мин. чтения

In a previous post, I shared about how to build a simple HTML app using FastAPI. Here, we’ll extend that app by adding functionality for checkboxes and a download button.

В предыдущем посте я рассказывал, как создать простое HTML-приложение с помощью FastAPI. Здесь мы расширим это приложение, добавив функциональность чекбоксов и кнопки скачивания.

Try it out with the GitHub repo here: fastapi-html

Попробуйте сами с помощью GitHub-репозитория: fastapi-html

Let’s allow users to alter results

Позволим пользователям изменять результаты

To demonstrate this, we’ll create a checkbox to multiply the input number by two, before spelling it out.

Для демонстрации мы создадим чекбокс, который умножает введённое число на два перед его преобразованием в текст.

Here’s the HTML for it, where we include a new input of type checkbox and its label. Note the name (multiply_by_2) and value (True) params—we’ll use it later in the post request.

Вот HTML-код для этого: мы добавляем новый input типа checkbox и его метку. Обратите внимание на параметры name (multiply_by_2) и value (True) — мы используем их далее в POST-запросе.

<!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=""/> <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"> </form> <p>Result: </p> </body> </html>

Sample Form

Result:

We’ll update our post request to take an additional param multiply_by_2 (from name). By default, the value is False; but if we check the checkbox, we get the value of True (from value). This boolean is passed into spell_number which handles the logic.

Мы обновим наш POST-запрос, добавив дополнительный параметр multiply_by_2 (из name). По умолчанию значение равно False, но если отметить чекбокс, мы получаем значение True (из value). Этот булев параметр передаётся в функцию spell_number, которая содержит основную логику.

@app.post('/checkbox') def form_post(request: Request, num: int = Form(...), multiply_by_2: bool = Form(False)): result = spell_number(num, multiply_by_2) return templates.TemplateResponse('checkbox.html', context={'request': request, 'result': result, 'num': num})

@app.post('/checkbox') def form_post(request: Request, num: int = Form(...), multiply_by_2: bool = Form(False)): result = spell_number(num, multiply_by_2) return templates.TemplateResponse('checkbox.html', context={'request': request, 'result': result, 'num': num})

Here are the results with and without checking the option.

Вот результаты с отмеченной и неотмеченной опцией.

Results with and without the "Multiply by 2" option

Результаты с включённой и выключенной опцией «Multiply by 2»

Let’s allow users to download results

Позволим пользователям скачивать результаты

After users view the results, they might want to download it. (In this scenario, it’s a really simple result. Nonetheless, a real app could provide results such as a csv of fraudulent purchases, a pdf report, or an ipython notebook.)

После просмотра результатов пользователь может захотеть их скачать. (В данном примере результат очень простой. Тем не менее реальное приложение может выдавать, например, CSV-файл с мошенническими покупками, PDF-отчёт или IPython-ноутбук.)

To achieve this, we’ll add a download button. Notice that we now have two inputs of type submit. As usual, we’ll use the name and value params.

Для этого мы добавим кнопку скачивания. Обратите внимание, что теперь у нас два элемента input типа submit. Как обычно, мы будем использовать параметры name и value.

<!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=""/> <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: </p> </body> </html>

Sample Form

Result:

We’ll update the post request with some basic logic to either return the result via HTML, or to download the file. Note that for FileResponse to work, we’ll need to install the aiofiles package.

Мы обновим POST-запрос, добавив простую логику для возврата результата через HTML или скачивания файла. Обратите внимание, что для работы FileResponse необходимо установить пакет aiofiles.

@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))

@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))

Here’s how the downloaded file looks like. It is named after the input query 1234.txt. The results will be the input query spelt out (possibly multiply by two).

Вот как выглядит скачанный файл. Он назван по введённому запросу — 1234.txt. Результат содержит введённое число, записанное словами (с возможным умножением на два).

The downloaded file (1234.txt) and the result (with "Multiply by 2")

Скачанный файл (1234.txt) и результат (с опцией «Multiply by 2»)

Try it out with the GitHub repo here: fastapi-html

Попробуйте сами с помощью GitHub-репозитория: fastapi-html

Next, we update our FastAPI app to let users:

• Select options via a checkbox
• Download results via a download button https://t.co/jFUmiMaud4

— Eugene Yan (@eugeneyan) August 7, 2020

Далее мы обновляем наше FastAPI-приложение, чтобы пользователи могли:• Выбирать опции через чекбокс• Скачивать результаты через кнопку загрузки https://t.co/jFUmiMaud4— Eugene Yan (@eugeneyan) August 7, 2020

If you found this useful, please cite this write-up as:

Если этот материал оказался полезным, пожалуйста, цитируйте его следующим образом:

Yan, Ziyou. (Aug 2020). Adding a Checkbox & Download Button to a FastAPI-HTML app. eugeneyan.com. https://eugeneyan.com/writing/fastapi-html-checkbox-download/.

Yan, Ziyou. (Aug 2020). Adding a Checkbox & Download Button to a FastAPI-HTML app. eugeneyan.com. https://eugeneyan.com/writing/fastapi-html-checkbox-download/.

or

или

@article{yan2020fastapi2, title = {Adding a Checkbox & Download Button to a FastAPI-HTML app}, author = {Yan, Ziyou}, journal = {eugeneyan.com}, year = {2020}, month = {Aug}, url = {https://eugeneyan.com/writing/fastapi-html-checkbox-download/} }

@article{yan2020fastapi2, title = {Adding a Checkbox & Download Button to a FastAPI-HTML app}, author = {Yan, Ziyou}, journal = {eugeneyan.com}, year = {2020}, month = {Aug}, url = {https://eugeneyan.com/writing/fastapi-html-checkbox-download/} }



Join 11,800+ readers getting updates on machine learning, RecSys, LLMs, and engineering.

Присоединяйтесь к 11 800+ читателям, получающим обновления о машинном обучении, RecSys, LLM и инженерии.