Skip to content

Instantly share code, notes, and snippets.

@wshayes
Created August 2, 2019 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wshayes/c62fcd9f5cd41f2f25442034470a54d9 to your computer and use it in GitHub Desktop.
Save wshayes/c62fcd9f5cd41f2f25442034470a54d9 to your computer and use it in GitHub Desktop.
[Pydantic subclassing] camelcasing aliases and json dumps #fastapi #pydantic
# 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