How to receive files and a non trivial data structure together? #85
-
I've been trying to work out how to receive an uploaded file and some data together in a POST request. For example I want to be able to POST a file and some configuration together with the configuration describing how the file should be processed. Here is a complete example of the sort of thing I'm trying to do
This works if you don't post any configuration. Ie like this:
But if you try to send some configuration along it doesn't work.
This happens because my_config is simply a string and there is nothing in the code to decode the json and turn it into a dict. I notice there is logic in the body handler which tries to decode strings into json, which presumably is to solve exactly this problem, but I need it to work for multipart requests as I need to send this information alongside the file upload. The openapi generated looks good to me:
And swagger gives you sensible default options when you go to try it out. but it doesn't work for exactly the same reason as curl doesn't. Am I fundamentally doing this incorrectly or should this be supported somehow? My ideas so far are:
Any thoughts would be really appreciated. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
@paulhirst-cb I did not find evidence that the But you can use Pre and per-item validators in Pydantic Model. Pydantic v2: class ExampleQuery(BaseModel):
my_file: FileStorage
my_config: Optional[MyConfiguration] = Field(None, description="Optional configuration")
@field_validator("my_config", mode="before")
def convert_to_dict(cls, v):
return json.loads(v) Pydantic v1: class ExampleQuery(BaseModel):
my_file: FileStorage
my_config: Optional[MyConfiguration] = Field(None, description="Optional configuration")
@validator("my_config", pre=True)
def convert_to_dict(cls, v):
return json.loads(v) |
Beta Was this translation helpful? Give feedback.
-
Since v2.5.1, |
Beta Was this translation helpful? Give feedback.
-
Thank you @luolingchun , that's really helpful of you to come back to an old thread and update me. I've updated to 2.5.1 and removed my validators and it's working perfectly! Cheers! |
Beta Was this translation helpful? Give feedback.
Since v2.5.1,
form
supports nesting structure by default and validator does not need to be used.