This is the 12th day of my participation in the August Text Challenge.More challenges in August
What is a Form?
You’ve probably heard of or seen HTMl form elements. The form form is the object FastApi uses to retrieve HTMl form elements.
Use Form forms in FastApi
Suppose we need to develop a login interface, the login page has a form, which contains two elements of user name and password, we need to determine whether the login is successful according to the form content returned from the front page.
The project structure
code
from fastapi import FastAPI
The Request context object is used to pass parameters between the front and back
from starlette.requests import Request
Import the Jinja2 template engine object for future use
from starlette.templating import Jinja2Templates
app=FastAPI()
Instantiate a template engine object and specify the path of the template
templates=Jinja2Templates(directory='templates')
Define the home page function to return to the login page
@app.get('/')
async def welcome(request:Request) :
return templates.TemplateResponse(name='login.html',context={'request':request})
Import the Form Form
from fastapi import Form
@app.post('/login/')
The view function receives the Form element in the body of the POST request
async def login(request:Request,username=Form(.),pwd=Form(.)) :
Logon logic demo
if username=='phyger' and pwd =='phyger666':
return templates.TemplateResponse(name='index.html',context={'request':request,'result':'SUCCESS'})
else:
return templates.TemplateResponse(name='index.html',context={'request':request,'result':'FAILED'})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='main:app',host='127.0.0.1',port=8765,reload=True)
Copy the code
Open the home page
http://localhost:8765/
Enter the correct user name and password
Incorrect user name and password
Analysis: We use FastApi Form objects to receive Form objects from the front end. The variable name used to receive the front-end form object must be the same as the name in the FROM form.
Attachment: login. HTML
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Login</title>
</head>
<body>
<form action="/login/" enctype="application/x-www-form-urlencoded" method="POST">
<table>
<tbody>
<tr><td>User name:</td><td><input type="text" name="username"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd"></td></tr>
</tbody>
</table>
<input type='submit' style="font-size: medium;">
</form>
</body>
</html>
Copy the code
Above, we briefly demonstrated the basic use of FastApi to handle Form forms.
Thank you for reading, don’t forget to follow, like, comment, forward four consecutive yo!