Skip to content

Commit

Permalink
Chore: Define Classes & Functions by adding DocString (#6)
Browse files Browse the repository at this point in the history
* Chore: Define Classes & Functions by adding `DocString`

* Fix Version
  • Loading branch information
yezz123 authored Dec 7, 2021
1 parent f406959 commit 1cebe1b
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
20 changes: 20 additions & 0 deletions pyngo/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,33 @@


def drf_error_details(exception: ValidationError) -> Dict[str, Any]:
"""
Convert a pydantic ValidationError into a DRF-style error response.
Args:
exception (ValidationError): The exception to convert.
Returns:
Dict[str, Any]: The error response.
"""
drf_data: Dict[str, Any] = {}
for error in exception.errors():
set_nested(drf_data, error["loc"], [error["msg"]])
return drf_data


def set_nested(data: Dict[str, Any], keys: Sequence[str], value: Any) -> None:
"""
Set a value in a nested dictionary.
Args:
data (Dict[str, Any]): The dictionary to set the value in.
keys (Sequence[str]): The keys to set the value at.
value (Any): The value to set.
Returns:
None
"""
for key in keys[:-1]:
data = data.setdefault(str(key), {})
data[keys[-1]] = value
29 changes: 29 additions & 0 deletions pyngo/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@
def openapi_params(
model_class: Type[BaseModel],
) -> List[ParameterDict]:
"""
Returns a list of parameters for the given model class.
Args:
model_class (Type[BaseModel]): The model class to get parameters for.
Raises:
ValueError: If the model class is not a pydantic model.
ValueError: If the model class has a field with an invalid location.
ValueError: If the model class has a field with allowEmptyValue set for a location other than 'query'.
ValueError: If the model class has a field with required set to False for a path parameter.
Returns:
List[ParameterDict]: A list of parameters for the given model class.
"""
parameters: List[ParameterDict] = []

for field in model_class.__fields__.values():
Expand All @@ -37,6 +52,20 @@ def openapi_params(


def _pydantic_field_to_parameter(field: ModelField) -> ParameterDict:
"""
Converts a pydantic field to an OpenAPI parameter.
Args:
field (ModelField): The field to convert.
Raises:
ValueError: If the field has an invalid location.
ValueError: If the field has allowEmptyValue set for a location other than 'query'.
ValueError: If the field has required set to False for a path parameter.
Returns:
ParameterDict: The converted field.
"""
location = field.field_info.extra.get("location", "query")
if location not in _VALID_LOCATIONS:
raise ValueError(f"location must be one of: {', '.join(_VALID_LOCATIONS)}")
Expand Down
35 changes: 35 additions & 0 deletions pyngo/querydict.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,24 @@ def get_origin(tp: Any) -> Optional[Any]:


class QueryDictModel(BaseModel):
"""
A model that can be initialized from a QueryDict.
This is a base class for models that can be initialized from a QueryDict.
The QueryDictModel class is a base class for models that can be initialized
from a QueryDict.
"""

@classmethod
def parse_obj(cls: Type["_QueryDictModel"], obj: Any) -> "_QueryDictModel":
"""
Parse a QueryDict into a model.
Returns:
A model that was initialized from the QueryDict.
"""
if isinstance(obj, QueryDict):
obj = querydict_to_dict(obj, cls)
return super().parse_obj(obj)
Expand All @@ -31,6 +47,16 @@ def querydict_to_dict(
query_dict: QueryDict,
model_class: Type[BaseModel],
) -> Dict[str, Any]:
"""
Convert a QueryDict into a dictionary.
Args:
query_dict (QueryDict): The QueryDict to convert.
model_class (Type[BaseModel]): The model class to use for the conversion.
Returns:
Dict[str, Any]: The converted dictionary.
"""
to_dict: Dict[str, Any] = {}
model_fields = model_class.__fields__

Expand All @@ -43,6 +69,15 @@ def querydict_to_dict(


def _is_list_field(field: ModelField) -> bool:
"""
Check if a field is a list field.
Args:
field (ModelField): The field to check.
Returns:
bool: True if the field is a list field, False otherwise.
"""
if sys.version_info >= (3, 7):
return get_origin(field.outer_type_) == list
else:
Expand Down

0 comments on commit 1cebe1b

Please sign in to comment.