Files
CTFd/CTFd/api/v1/helpers/schemas.py
Ife Lawal 03e546e9f0 Pydantic documentation Fixes #1829 (#1871)
- Improved the `sqlalchemy_to_pydantic` function to accept additional schema fields on top of the SQLAlchemy model fields
- Added the solves and solved_by_me fields to the Swagger documentation (Closes #1829)
2021-04-26 14:00:04 -04:00

38 lines
1.2 KiB
Python

from typing import Container, Dict, Type
from pydantic import BaseModel, create_model
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.properties import ColumnProperty
def sqlalchemy_to_pydantic(
db_model: Type, *, include: Dict[str, type] = None, exclude: Container[str] = None
) -> Type[BaseModel]:
"""
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
"""
if exclude is None:
exclude = []
mapper = inspect(db_model)
fields = {}
for attr in mapper.attrs:
if isinstance(attr, ColumnProperty):
if attr.columns:
column = attr.columns[0]
python_type = column.type.python_type
name = attr.key
if name in exclude:
continue
default = None
if column.default is None and not column.nullable:
default = ...
fields[name] = (python_type, default)
if bool(include):
for name, python_type in include.items():
default = None
fields[name] = (python_type, default)
pydantic_model = create_model(
db_model.__name__, **fields # type: ignore
)
return pydantic_model