Skip to main content

Pydantic Package for Adding Models into a Django or Django Rest Framework Project ✨

Project description

Pyngo :snake:

Utils to help integrate pydantic into Django projects

Test Package version Supported Python versions Test


Installation

You can add pyngo in a few easy steps. First of all, install the dependency:

$ pip install pyngo

---> 100%

Successfully installed pyngo

Features 🎉

  • Using Pydantic to Build your Models in Django Project.
  • Using OpenAPI utilities to build params from a basic model.
  • using QueryDictModel to build Pydantic models from a QueryDict object.
  • propagate any errors from Pydantic in Django Rest Framework.
  • Tested in Python 3.10 and up.

Examples 📚

OpenAPI

  • pyngo.openapi_params() can build params from a basic model
from pydantic import BaseModel
from pyngo import openapi_params

class Model(BaseModel):
   bingo: int

print(openapi_params(Model))
  • pyngo.ParameterDict.required is set according to the type of the variable
from typing import Optional
from pydantic import BaseModel
from pyngo import openapi_params

class Model(BaseModel):
   required_param: int
   optional_param: Optional[int]

print(openapi_params(Model))

Other fields can be set through the field’s info:

from pydantic import BaseModel, Field
from pyngo import openapi_params

class WithDescription(BaseModel):
   described_param: str = Field(
      description="Hello World Use Me!"
   )

class InPath(BaseModel):
   path_param: str = Field(location="path")

class WithDeprecated(BaseModel):
   deprecated_field: bool = Field(deprecated=True)

class WithNoAllowEmpty(BaseModel):
   can_be_empty: bool = Field(allowEmptyValue=False)

print(openapi_params(WithDescription)[0]["description"])
print(openapi_params(InPath)[0]["in"])
print(openapi_params(WithDeprecated)[0]["deprecated"])
print(openapi_params(WithNoAllowEmpty)[0]["allowEmptyValue"])

Django

  • pyngo.querydict_to_dict() and pyngo.QueryDictModel are conveniences for building a pydantic.BaseModel from a django.QueryDict.
from typing import List
from django.http import QueryDict
from pydantic import BaseModel
from pyngo import QueryDictModel, querydict_to_dict

class Model(BaseModel):
   single_param: int
   list_param: List[str]

class QueryModel(QueryDictModel):
   single_param: int
   list_param: List[str]

query_dict = QueryDict("single_param=20&list_param=Life")

print(Model.model_validate(querydict_to_dict(query_dict, Model)))
print(QueryModel.model_validate(query_dict))

Note: Don't forget to Setup the Django Project.

Django Rest Framework

  • pyngo.drf_error_details() will propagate any errors from Pydantic.
from pydantic import BaseModel, ValidationError
from pyngo import drf_error_details

class Model(BaseModel):
   foo: int
   bar: str

data = {"foo": "Cat"}

try:
   Model.parse_obj(data)
except ValidationError as e:
   print(drf_error_details(e))

Errors descend into nested fields:

from typing import List
from pydantic import BaseModel, ValidationError
from pyngo import drf_error_details

class Framework(BaseModel):
   frm_id: int

class Language(BaseModel):
   framework: List[Framework]

data = {"framework": [{"frm_id": "not_a_number"}, {}]}
expected_details = {
   "framework": {
      "0": {"frm_id": ["value is not a valid integer"]},
      "1": {"frm_id": ["field required"]},
   }
}

try:
   Language.model_validate(data)
except ValidationError as e:
   print(drf_error_details(e))

Development 🚧

Setup environment 📦

You should create a virtual environment and activate it:

python -m venv venv/
source venv/bin/activate

And then install the development dependencies:

# Install dependencies
pip install -e .[test,lint]

Run tests 🌝

You can run all the tests with:

bash scripts/test.sh

Note: You can also generate a coverage report with:

bash scripts/test_html.sh

Format the code 🍂

Execute the following command to apply pre-commit formatting:

bash scripts/format.sh

Execute the following command to apply mypy type checking:

bash scripts/lint.sh

License 🍻

This project is licensed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyngo-2.2.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

pyngo-2.2.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file pyngo-2.2.0.tar.gz.

File metadata

  • Download URL: pyngo-2.2.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.12.4

File hashes

Hashes for pyngo-2.2.0.tar.gz
Algorithm Hash digest
SHA256 8be6131602f6b9ef0f3c07df927f30ddcad226247c57eb05c1c15a2af64d0842
MD5 debb4e2b53bab973bb9a9e171c53be9d
BLAKE2b-256 0c79ac6b3de39e87293fbe0bc596329cec5f4404ababe5fec4011c28e7f2ba22

See more details on using hashes here.

File details

Details for the file pyngo-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: pyngo-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 7.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.12.4

File hashes

Hashes for pyngo-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3fcdb7292f8b3aaff14c6d75a128c8deb16c9f7117840614133739cde26ea666
MD5 72a081f704ed3d8d6982b9c7bca9c3f1
BLAKE2b-256 f0829700ca31096bd2c4f02c7536cc076e072eacc0dbae88d9adcbe59747801d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page