0

i wanna validate data in request i have dictionary (a and b are use cases, 1234 are sub use cases)

d ={'a':[1,2],'b':[3,4]}

and request @router.post("/documents")

from typing import Literal, List, Optional, Dict

@router.post("/documents")
async def data(usecase: Literal[frozenset(d.keys())] = Form(...))

it works and allowed values only a and b

But i wanna extend validation

@router.post("/documents")
    async def data(usecase: Literal[frozenset(d.keys())] = Form(...),
                   subusecase: THERE I WANNA VALIDATE 1234 VALUES  = Form(...)
                   )

I will be very grateful for the help

  • `class Usecase: a: Literal[1, 2, 3, 4], b: Literal[1, 2, 3, 4]`? Then use that as the type of the request? You can also define the Literal sequence as a variable, then re-used that for both values; `subusecases = Literal[1, 2, 3, 4], class Usecase: a: subusecases, b: subusecases` – MatsLindh Nov 14 '21 at 23:07
  • Thank you for your attention to my issue. I wanna use exactly dict d. my expectations it should by something like this subusecase: Dict[usecase]: str = Form(...) – Alexander Vedmed' Nov 14 '21 at 23:15

1 Answers1

0

I'm not sure i quite understand the structure of the data received by your route.

If you want to validate the route input from a complexe structure like nested dict etc, in my opinion it would be beter to use a pydantic model with a pydantic validation function.

you pass to your route a pydantic model as parameter:

@router.post("/documents")
async def data(use_cases: UseCases):
    #  do something with your uses_cases
    pass

pydantic model example:

from typing import List

from pydantic import BaseModel, validator


class UseCases(BaseModel):
    a: List[int]
    b: List[int]

    @validator('a')
    def a_must_containt_something(cls, v):
        #  add your validations here
        return v

    @validator('b')
    def b_must_containt_something(cls, v):
        #  add your validations here
        return v
Bastien B
  • 1,018
  • 8
  • 25