1

I use a pydantic class to create a profile with field validations like email for example. When I create a single profile, these validations are necessary. But when I massively add dozens of profiles to a list of profiles, I would like this validation to disappear because I will later check each profile by browsing the list. The idea is that I don't want a massive scrap to be stopped if a profile isn't good. We know that sometimes scrap has waste.

I don't want to loose Email validation when creating 1 profil

How do you do this please?

class Profil(BaseModel):
    pseudo: str
    mail: EmailStr
    page_url: str
    social_network: str
    created_date: datetime = Field(default_factory=datetime.now)

In my DTO file for bulk insert where I don't want Raise ValueError if email is not correct


class InsertListProfilInputDto(BaseModel):
    """Input Dto for bulk insert of profil"""

    data: list[Profil]

Thank you

3
  • What version of pydantic are you using 1.x, 2x? Can you show how you define EmailStr? Commented Mar 22, 2024 at 10:43
  • I'm not sur to understand. I Just define the type EmailSTr and pydantic validate the email format. from pydantic import BaseModel, EmailStr, Field I use pydantic 2.xx Commented Mar 22, 2024 at 10:50
  • could you provide a concrete example? I mean a fully reproducible example Commented Mar 22, 2024 at 11:04

1 Answer 1

0
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field


class Influenceur(BaseModel):
   pseudo: str
   mail: EmailStr
   page_url: str
   social_network: str
   created_date: datetime = Field(default_factory=datetime.now)


class BulkInsertInfluenceurInputDto(BaseModel):
    data: list[Influenceur]

    @model_validator(mode="wrap")  # type: ignore
    def bypass_incorrect_profil(cls, kwargs: dict[str, Any], handler):
        for profil in kwargs["data"][:]:
            try:
                Influenceur(**profil)
            except Exception:
                kwargs["data"].remove(profil)
        return handler(kwargs)

In my endpoint with fast fastapi with this datas in body

{
  "data": [
    {
      "pseudo": "bob",
      "mail": "[email protected]",
      "page_url": "http://example.com",
      "social_network": "instagram",
      "created_date": "2024-03-22T11:06:44.002Z"
    },
{
      "pseudo": "marc",
      "mail": "marcexample.com", -------> this emailis Wrong and will raise Error in Influenceur.mail : EmailStr
      "page_url": "http://example.com",
      "social_network": "instagram",
      "created_date": "2024-03-22T11:06:44.002Z"
    }
  ]
}


@router.post("/")
async def bulk_insert(input_dto: BulkInsertInfluenceurInputDto):
    print(input_dto)

results only bob (correct email ) is returned:

[{'pseudo': 'bob', 'mail': '[email protected]', 'page_url': 'http://example.com', 'social_network': 'instagram', 'created_date': '2024-03-22T11:06:44.002Z'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.