Handling Form Submission
This guide walks you through the process of using Inspira to create and submit a web form.
Create a new directory for your project
$ mkdir form_submission
$ cd form_submission
Create and activate a virtual environment
$ python -m venv venv
$ source venv/bin/activate
Install Inspira
$ pip install inspira
Project Initialization
To begin your project, initiate it by executing the following command:
$ inspira init
Generating Controller
Generate necessary resources for your project by running the following command:
$ inspira new controller greeting
Creating the Templates Folder
In the project's main directory, create a folder named templates
alongside the main.py
file.
Generate two files, index.html
and result.html
, within the newly created folder using the commands below:
$ mkdir templates
$ touch templates/index.html
$ touch templates/result.html
Now, insert the provided content into the index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="" method="post">
<p>Name: <input type="text" name="name"/></p>
<p>Email: <input type="email" name="email"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
Additionally, add the following content to the result.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Result</h1>
<p>Name: {{ name }}</p>
<p>Email: {{ email }}</p>
<a href="/greeting">Submit another message</a>
</body>
</html>
Controller Modifications
Open greeting_controller.py
and apply the following changes:
from inspira.decorators.http_methods import get, post
from inspira.decorators.path import path
from inspira.responses import TemplateResponse
from inspira.requests import Request
@path("/greeting")
class GreetingController:
@get()
async def index(self, request: Request):
return TemplateResponse("index.html")
@post()
async def post_form(self, request: Request):
form = await request.form()
name = form['name']
email = form['email']
context = {
"name": name,
"email": email
}
return TemplateResponse("result.html", context)
Launching the Server
Initiate the server with the following command:
$ uvicorn main:app --reload
Testing the Service
Visit http://localhost:8000/greeting
in your browser to interact with the form.
Enter the required details and submit the form for results.
Submit a name
and email
to see the results:
Summary
Congratulations! You have just used Inspira to create and submit a form.
The code is available on GitHub Happy coding!