Skip to main content

Utils to help integrate pydantic into Django projects

Project description

Pyngo

Pyngo

Utils to help integrate pydantic into Django projects

codecov PyPI version License Language framework Pypi


Install the project: pip install 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.6 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.parse_obj(querydict_to_dict(query_dict, Model)))
print(QueryModel.parse_obj(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:
   Framework.parse_obj(data)
except ValidationError as e:
   print(drf_error_details(e))

Development 🚧

You should create a virtual environment and activate it:

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

And then install the development dependencies:

pip install -r requirements.dev.txt

Test the code 📚

For Building the tests i use pytest, you can run it using a pre-configured command:

make test

Format the code 💅

Execute the following command to apply pre-commit formatting:

make lint

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-1.1.0.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

pyngo-1.1.0-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pyngo-1.1.0.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for pyngo-1.1.0.tar.gz
Algorithm Hash digest
SHA256 3691646bfedd0f6a0b72d302b63fb0b7bb49563bee5050ebd64aee18a000bbc7
MD5 6ab90f5735fe7f1dad1a4abaf6b3260b
BLAKE2b-256 f165038a8da34af86ad212f8e171a4e4ced2f64538d8f8070781a9d8fc5582e6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pyngo-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for pyngo-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a0131c48a8eedd21aba2949b6db6b9c7ae8c403b83250a9ec33346c79bb14951
MD5 1b93d6c8731314b02156e1ae27ef568b
BLAKE2b-256 105b7478236b49610a44b64c83f8262c3362b8652f44f9591d8380da0b2ee56f

See more details on using hashes here.

Supported by

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