Created
August 2, 2019 11:07
-
-
Save wshayes/c62fcd9f5cd41f2f25442034470a54d9 to your computer and use it in GitHub Desktop.
[Pydantic subclassing] camelcasing aliases and json dumps #fastapi #pydantic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://github.com/tiangolo/fastapi/issues/413#issuecomment-517504748 | |
# @Rehket for what it's worth, I recommend subclassing BaseModel and using that as the root for all of your API models (to reduce code repetition). For example, I use a base class that mostly looks like this: | |
import re | |
from functools import partial | |
from typing import Any, Dict | |
from fastapi.encoders import jsonable_encoder | |
from pydantic import BaseConfig, BaseModel | |
def snake2camel(snake: str, start_lower: bool = False) -> str: | |
camel = snake.title() | |
camel = re.sub("([0-9A-Za-z])_(?=[0-9A-Z])", lambda m: m.group(1), camel) | |
if start_lower: | |
camel = re.sub("(^_*[A-Z])", lambda m: m.group(1).lower(), camel) | |
return camel | |
class APIModel(BaseModel): | |
class Config(BaseConfig): | |
orm_mode = True | |
allow_population_by_alias = True | |
alias_generator = partial(snake2camel, start_lower=True) | |
def dump_obj(self, **jsonable_encoder_kwargs: Any) -> Dict[str, Any]: | |
return jsonable_encoder(self, **jsonable_encoder_kwargs) | |
# Then I can do | |
class UserCreate(APIModel): | |
user_id: uuid.UUID | |
password: str | |
# and get automatic generation of camelcase aliases, and have the dump_obj method (which generates a more json-dumps-friendly dict than model.dict(), which, for example, doesn't). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment