简体   繁体   中英

Read dynamic FormData with FastApi

I can read JS FormData with Python FastAPI from my HTML code like this:

<form>
 <input type ="number" name="test1">
</form>

Python FastAPI:

@app.post("/zip")
async def buildScaffolding( test1: int=Form(...)):
    print(test1)
    return ""

But now I want to change the HTML form dynamically. Like when you buy items in a shop:

<form>
 <input type ="number" name="numberItems">
 <!-- item 1-->
 <input type ="text" name="item_1">
 <!-- item 2-->
 <input type ="text" name="item_2">
 ...
 <!-- item n-->
 <input type ="text" name="item_n">
</form>

Question: How can I process the input with Python FastAPI, if I don´t know how many items will be sent?

Below code will help you to get dynamic form data.


@app.post("/zip")
async def buildScaffolding(request: Request):
    form_data = await request.form()
    print(form_data)
    return ""

You can create an Enum dynamically, this will let you create your query parameters dynamically.

from fastapi import FastAPI, Form
from enum import Enum

app = FastAPI()

DynamicEnum = Enum("DynamicEnum", names={"item1":"items", "item2": "comes", "item3": "from", "item4": "database"})


@app.post("/select")
async def select_item(item: DynamicEnum = Form(...)):
    return item

Let's check the /docs and make sure FastAPI rendered that correctly.

在此处输入图片说明

In the current case, we dont know how many inputs, to keep it simple, in the case of dynamically created inputs, it is preferrable to take request as request contains form which is added once we press submit or enter. That means, after submitting whatever the input is, the request will carry it as form to the api.

from fastapi.encoders import jsonable_encoder
@app.post('/check')
async def check(request: Request):
    da = await request.form()
    da = jsonable_encoder(da)
    print(da)
    return da

we can use jsonable_encoder to convert the form inputs into json format. curl it to check how it works. for example,

curl -i -d "param1=value1&param2=value2" http://localhost:8000/check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM