How to use python keywords in model defing with Pydantic? - python

I want to define a model like this:
class Item(BaseModel):
class: str
pass: float
Since "class" and "pass" are python keywords this will fail.
Use marshmallow can do this by using data_key:
class Item(Schema):
class_ = fields.String(data_key="class")
pass_ = fields.Float(data_key="pass")
Does pydantic has something like "data_key" or there are other ways to achieve the same goal?Thanks for answering

I can give you another option.
class Item(BaseModel):
class_: str
pass_: float
class Config:
fields = {
'class_': 'class'
'pass_': 'pass'
}

Related

Either of the two Pydantic attributes should be optional

I want validate a payload schema & I am using Pydantic to do that. The class created by inheriting Pydantic's BaseModel is named as PayloadValidator and it has two attributes, addCustomPages which is list of dictionaries & deleteCustomPages which is a list of strings.
class NestedCustomPages(BaseModel):
"""This is the schema for each custom page."""
html: str
label: str
type: int
class PayloadValidator(BaseModelWithContext):
"""This class defines the payload load schema and also validates it."""
addCustomPages: Optional[List[NestedCustomPages]]
deleteCustomPages: Optional[List[str]]
I want to declare either of the attributes of class PayloadValidator as optional. I have tried looking for the solution for this but couldn't find anything.
There was a question on this a while ago on the pydantic Github page: https://github.com/samuelcolvin/pydantic/issues/506. The conclusion there includes a toy example with a model that requires either a or b to be filled by using a validator:
from typing import Optional
from pydantic import validator
from pydantic.main import BaseModel
class MyModel(BaseModel):
a: Optional[str] = None
b: Optional[str] = None
#validator('b', always=True)
def check_a_or_b(cls, b, values):
if not values.get('a') and not b:
raise ValueError('Either a or b is required')
return b
mm = MyModel()

How to access **kwargs in Pydantic's validator method

I wanted to validate the below stated payload -
payload = {
"emailId":['jeet#steinnlabs.com', 'jeet#dope.security'],
"role":"Administrator",
}
Hence, I created a class using Pydantic's BaseModel like this -
class SendInvitePayloadValidator(BaseModel):
emailId: List[str]
role: str
class Config:
extra = Extra.forbid
#validator('emailId')
def validate_email(cls, emailID):
pass
Now, I also wanted to validate each key of payload e.g emailId but in order to do that I need another an extra value lets say tenantId.
If I include tenantId in the model then the payload validation won't work.
So is there a way I could just pass few extra values to the validator method?

Passing python class object to bottle template

My class looks like this:
class Person:
def __init__(name=None, id_=None):
self.name = name
self.id_ = id_
# I'm currently doing this. member object is of Person type.
return template('index.html', name=member.name, id_=member.id_)
# What I want to do
return template('index.html', member=member)
First way is fine when we don't have many attributes to deal, but my class currently has around 10 attributes and it doesn't look good to pass so many parameters to template function. Now I want to pass an object of this class to bottle template and use it there. How can I do it?
# What I want to do
return template('index.html', member=member)
Just do that. It should work fine. In your template, you'll simply reference member.name, member.id_, etc.
If you have python 3.7+
from dataclasses import dataclass, asdict
#dataclass
class Person:
name: str
id_: str
member = Person('toto', '1')
return template('index.html', **asdict(member))
But maybe its more interesting to inject your object directly in your template.

How to decode json with reserved name as key using json_dataclass?

I am trying to decode a json I received from an api using dataclass_json from the dataclasses_json module, however one of the json fields is called class which is a python reserved keyword. How can I define them?
{'some_var': False,
'class': '/12345.jpg'}
I tried this
#dataclass_json
#dataclass
class Media:
some_var: str
class: str ### error because class is a reserved keyword
parsedObject = Media.from_json(jsonString)
but get an error due to 'class' being a reserved keyword.
Specify the original field name as a field_name and name your class property differently:
from dataclasses import dataclass, field
from dataclasses_json import config, dataclass_json
#dataclass_json
#dataclass
class Media:
some_var: str
the_class: str = field(metadata=config(field_name="class"))
Check out the docs, scroll down to "Encode or decode using a different name".

How to validate JSON field with name "from"

I want to validate JSON object (it is in Telegram Bot API) which contains from field (which is reserved word in Python) by using pydantic validator. So my model should look like the following:
class Message(BaseModel):
message_id: int
from: Optional[str]
date: int
chat: Any
...
But using from keyword is not allowed in this context.
How could I do this?
Note: this is different than "Why we can't use keywords as attributes" because here we get external JSON we don't control and we anyway should handle JSON with from field.
I believe you can replace from with from_.
You can do it like this:
class Message(BaseModel):
message_id: int
from_: Optional[str]
date: int
chat: Any
class Config:
fields = {
'from_': 'from'
}
...
There might be a way to do this using a class statement, but I didn't see anything in a quick skim of the documentation. What you could do is use dynamic model creation instead.
fields = {
'message_id': (int,),
'from': (Optional[str], ...),
'date': (int, ...),
'chat': (Any, ...)
}
Message = create_model("Message", **fields)

Categories