flask-dantic


Nameflask-dantic JSON
Version 0.0.7 PyPI version JSON
download
home_pagehttps://github.com/vivekkeshore/flask-dantic
SummaryThis package provides a utility to validate pydantic request models and also serialize db object using pydantic models.
upload_time2023-07-01 20:00:35
maintainer
docs_urlNone
authorVivek Keshore
requires_python>=3.6
licenseMIT
keywords sqlalchemy alchemy mysql postgres flask mssql sql sqlite serialize pydantic validate request orm serialization performance database relational
VCS
bugtrack_url
requirements pydantic pytest sqlalchemy setuptools flask werkzeug
Travis-CI No Travis.
coveralls test coverage
            # 🅕🅛🅐🅢🅚-🅓🅐🅝🅣🅘🅒

*Flask-Dantic* is a Python package that would enable users to use Pydantic models for validations and serialization, thus making it easy to link Flask with Pydantic.
It can validate the request params, query args and path args.

Also, the package provides a serializer that serializes the database objects using the pydantic models. 
This comes handy if you are using pydantic models for request and response in Flask.

A single serialize call will take care of validating the returned response as well as serializing it. There are options to include or exclude certain fields or exclude/include fields with null values.

[![PyPI](https://img.shields.io/pypi/v/flask-dantic?color=g)](https://pypi.org/project/flask-dantic/)
![Codecov](https://img.shields.io/codecov/c/github/vivekkeshore/flask-dantic)
[![Python package](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml/badge.svg)](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml)
![LGTM Grade](https://img.shields.io/lgtm/grade/python/github/vivekkeshore/flask-dantic)
[![GitHub license](https://img.shields.io/github/license/vivekkeshore/flask-dantic)](https://github.com/vivekkeshore/flask-dantic)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/flask-dantic)
![Snyk Vulnerabilities for GitHub Repo](https://img.shields.io/snyk/vulnerabilities/github/vivekkeshore/flask-dantic)
![GitHub repo size](https://img.shields.io/github/repo-size/vivekkeshore/flask-dantic)

----

### Compatibility


This package is compatible with Python >= 3.6

## Installation


Install with pip:

```bash
    pip install flask-dantic
```

## Examples
### Validating body parameters

```python
# Using the Pydantic model for request.
from typing import Optional

from flask import current_app as flask_app, request
from pydantic import BaseModel

from flask_dantic import pydantic_validator


class UserCreateModel(BaseModel):
    username: str
    age: Optional[int] = None
    phone: Optional[str] = None


@flask_app.route("/user/create", methods=["POST"])
@pydantic_validator(body=UserCreateModel)  # Pass the model against body kwarg.
def create_user():
    """
        Request Json to create user that will be validated against UserModel
        {
            "username": "Foo",
            "age": 42,
            "phone": "123-456-7890"
        }
    """
    user_model = request.body_model
    print(user_model.username, user_model.age, user_model.phone)
```

### Change the default validation error status code. Default status code is 422
```python

@flask_app.route("/user/create", methods=["POST"])
# Changing the default validation error status code from default 422 to 400
@pydantic_validator(body=UserCreateModel, validation_error_status_code=400)
def create_user():
    """
        Request Json to create user that will be validated against UserModel
        {
            "username": "Foo",
            "age": 42,
            "phone": "123-456-7890"
        }
    """
    user_model = request.body_model
    print(user_model.username, user_model.age, user_model.phone)
```

### Validating Query args - request.args

```python
# Using the Pydantic model for request.
from typing import Optional

from flask import current_app as flask_app, request
from pydantic import BaseModel

from flask_dantic import pydantic_validator


# Sample url - https://localhost:5000/user/get?username=Foo&age=42
# Here username and foo are pass are query args

class UserQueryModel(BaseModel):
    username: str
    age: Optional[int] = None


@flask_app.route("/user/get", methods=["GET"])
@pydantic_validator(query=UserQueryModel)  # Pass the model against query kwarg
def get_user():
    user_query_model = request.query_model
    print(user_query_model.username, user_query_model.age)
```


### Validating URL Path args

```python
# Using the Pydantic model for request.

from flask import current_app as flask_app, request
from pydantic import BaseModel, Field

from flask_dantic import pydantic_validator

# Sample url - https://localhost:5000/user/get/c55926d3-cbd0-4eea-963b-0bcfc5c40d46
# Here the uuid is the dynamic path param.

UUID_REGEX = "[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"


class UserPathParamModel(BaseModel):
    user_id: str = Field(..., regex=UUID_REGEX, description="ID of the user")


@flask_app.route("/user/get/<string:user_id>", methods=["GET"])
@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params
def get_user(user_id):
    path_param_model = request.path_param_model
    print(path_param_model.user_id)
```


### Serialization using Pydantic module and returning the response.


```python
from sqlalchemy import create_engine
from sqlalchemy.orm import Session


db_engine = create_engine(DB_CONNECT_STRING)  # DB connection string, ex "sqlite:///my_app.db"
db = Session(db_engine)
```

```python
from http import HTTPStatus
from typing import Optional

from flask import current_app as flask_app, jsonify
from pydantic import BaseModel

from flask_dantic import serialize, pydantic_validator


class UserResponseModel(BaseModel):  # Define the pydantic model for serialization.
    username: str
    age: Optional[int] = None
    phone: Optional[str] = None


@flask_app.route("/user/list", methods=["GET"])
def get_all_users():
    users = get_all_users_from_db()

    # Pass the db records and pydantic model to serialize method. Set many as True if there are multiple records.
    serialized_users = serialize(users, UserResponseModel, many=True)  # Serialize call
    return jsonify(serialized_users), HTTPStatus.OK


@flask_app.route("/user/get/<string:user_id>", methods=["GET"])
@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params
def get_user(user_id):
    user = get_single_user_by_id(user_id)

    # Pass the db record and pydantic model to serialize method. Many is set to False by default.
    user = serialize(user, UserResponseModel)  # Serialize call
    return jsonify(user), HTTPStatus.OK
```

### Serialization - Dump directly to json. This is useful when you want to return the response as json without flask jsonify.

```python
from flask_dantic import serialize

# Taking the same example from above. Modifying the serialize call.
@flask_app.route("/user/get/<string:user_id>", methods=["GET"])
@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params
def get_user(user_id):
    user = get_single_user_by_id(user_id)

    # Pass the db record and pydantic model to serialize method. Many is set to False by default.
      # Serialize call
    return serialize(user, UserResponseModel, json_dump=True), HTTPStatus.OK
```

Tests
-----

Run tests:

```bash
    pytest
```


License
-------

Flask-Dantic is released under the MIT License. See the bundled [`LICENSE`](https://github.com/vivekkeshore/flask-dantic/blob/main/LICENSE) file
for details.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/vivekkeshore/flask-dantic",
    "name": "flask-dantic",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "sqlalchemy,alchemy,mysql,postgres,flask,mssql,sql,sqlite,serialize,pydantic,validate,request,orm,serialization,performance,database,relational",
    "author": "Vivek Keshore",
    "author_email": "vivek.keshore@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/57/4f/4643120ae88bb9b0aa0e226905644a33113b1e1b96f316b376eec9104f54/flask-dantic-0.0.7.tar.gz",
    "platform": "any",
    "description": "# \ud83c\udd55\ud83c\udd5b\ud83c\udd50\ud83c\udd62\ud83c\udd5a-\ud83c\udd53\ud83c\udd50\ud83c\udd5d\ud83c\udd63\ud83c\udd58\ud83c\udd52\n\n*Flask-Dantic* is a Python package that would enable users to use Pydantic models for validations and serialization, thus making it easy to link Flask with Pydantic.\nIt can validate the request params, query args and path args.\n\nAlso, the package provides a serializer that serializes the database objects using the pydantic models. \nThis comes handy if you are using pydantic models for request and response in Flask.\n\nA single serialize call will take care of validating the returned response as well as serializing it. There are options to include or exclude certain fields or exclude/include fields with null values.\n\n[![PyPI](https://img.shields.io/pypi/v/flask-dantic?color=g)](https://pypi.org/project/flask-dantic/)\n![Codecov](https://img.shields.io/codecov/c/github/vivekkeshore/flask-dantic)\n[![Python package](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml/badge.svg)](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml)\n![LGTM Grade](https://img.shields.io/lgtm/grade/python/github/vivekkeshore/flask-dantic)\n[![GitHub license](https://img.shields.io/github/license/vivekkeshore/flask-dantic)](https://github.com/vivekkeshore/flask-dantic)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/flask-dantic)\n![Snyk Vulnerabilities for GitHub Repo](https://img.shields.io/snyk/vulnerabilities/github/vivekkeshore/flask-dantic)\n![GitHub repo size](https://img.shields.io/github/repo-size/vivekkeshore/flask-dantic)\n\n----\n\n### Compatibility\n\n\nThis package is compatible with Python >= 3.6\n\n## Installation\n\n\nInstall with pip:\n\n```bash\n    pip install flask-dantic\n```\n\n## Examples\n### Validating body parameters\n\n```python\n# Using the Pydantic model for request.\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel\n\nfrom flask_dantic import pydantic_validator\n\n\nclass UserCreateModel(BaseModel):\n    username: str\n    age: Optional[int] = None\n    phone: Optional[str] = None\n\n\n@flask_app.route(\"/user/create\", methods=[\"POST\"])\n@pydantic_validator(body=UserCreateModel)  # Pass the model against body kwarg.\ndef create_user():\n    \"\"\"\n        Request Json to create user that will be validated against UserModel\n        {\n            \"username\": \"Foo\",\n            \"age\": 42,\n            \"phone\": \"123-456-7890\"\n        }\n    \"\"\"\n    user_model = request.body_model\n    print(user_model.username, user_model.age, user_model.phone)\n```\n\n### Change the default validation error status code. Default status code is 422\n```python\n\n@flask_app.route(\"/user/create\", methods=[\"POST\"])\n# Changing the default validation error status code from default 422 to 400\n@pydantic_validator(body=UserCreateModel, validation_error_status_code=400)\ndef create_user():\n    \"\"\"\n        Request Json to create user that will be validated against UserModel\n        {\n            \"username\": \"Foo\",\n            \"age\": 42,\n            \"phone\": \"123-456-7890\"\n        }\n    \"\"\"\n    user_model = request.body_model\n    print(user_model.username, user_model.age, user_model.phone)\n```\n\n### Validating Query args - request.args\n\n```python\n# Using the Pydantic model for request.\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel\n\nfrom flask_dantic import pydantic_validator\n\n\n# Sample url - https://localhost:5000/user/get?username=Foo&age=42\n# Here username and foo are pass are query args\n\nclass UserQueryModel(BaseModel):\n    username: str\n    age: Optional[int] = None\n\n\n@flask_app.route(\"/user/get\", methods=[\"GET\"])\n@pydantic_validator(query=UserQueryModel)  # Pass the model against query kwarg\ndef get_user():\n    user_query_model = request.query_model\n    print(user_query_model.username, user_query_model.age)\n```\n\n\n### Validating URL Path args\n\n```python\n# Using the Pydantic model for request.\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel, Field\n\nfrom flask_dantic import pydantic_validator\n\n# Sample url - https://localhost:5000/user/get/c55926d3-cbd0-4eea-963b-0bcfc5c40d46\n# Here the uuid is the dynamic path param.\n\nUUID_REGEX = \"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\"\n\n\nclass UserPathParamModel(BaseModel):\n    user_id: str = Field(..., regex=UUID_REGEX, description=\"ID of the user\")\n\n\n@flask_app.route(\"/user/get/<string:user_id>\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    path_param_model = request.path_param_model\n    print(path_param_model.user_id)\n```\n\n\n### Serialization using Pydantic module and returning the response.\n\n\n```python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\n\ndb_engine = create_engine(DB_CONNECT_STRING)  # DB connection string, ex \"sqlite:///my_app.db\"\ndb = Session(db_engine)\n```\n\n```python\nfrom http import HTTPStatus\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, jsonify\nfrom pydantic import BaseModel\n\nfrom flask_dantic import serialize, pydantic_validator\n\n\nclass UserResponseModel(BaseModel):  # Define the pydantic model for serialization.\n    username: str\n    age: Optional[int] = None\n    phone: Optional[str] = None\n\n\n@flask_app.route(\"/user/list\", methods=[\"GET\"])\ndef get_all_users():\n    users = get_all_users_from_db()\n\n    # Pass the db records and pydantic model to serialize method. Set many as True if there are multiple records.\n    serialized_users = serialize(users, UserResponseModel, many=True)  # Serialize call\n    return jsonify(serialized_users), HTTPStatus.OK\n\n\n@flask_app.route(\"/user/get/<string:user_id>\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    user = get_single_user_by_id(user_id)\n\n    # Pass the db record and pydantic model to serialize method. Many is set to False by default.\n    user = serialize(user, UserResponseModel)  # Serialize call\n    return jsonify(user), HTTPStatus.OK\n```\n\n### Serialization - Dump directly to json. This is useful when you want to return the response as json without flask jsonify.\n\n```python\nfrom flask_dantic import serialize\n\n# Taking the same example from above. Modifying the serialize call.\n@flask_app.route(\"/user/get/<string:user_id>\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    user = get_single_user_by_id(user_id)\n\n    # Pass the db record and pydantic model to serialize method. Many is set to False by default.\n      # Serialize call\n    return serialize(user, UserResponseModel, json_dump=True), HTTPStatus.OK\n```\n\nTests\n-----\n\nRun tests:\n\n```bash\n    pytest\n```\n\n\nLicense\n-------\n\nFlask-Dantic is released under the MIT License. See the bundled [`LICENSE`](https://github.com/vivekkeshore/flask-dantic/blob/main/LICENSE) file\nfor details.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "This package provides a utility to validate pydantic request models and also serialize db object using pydantic models.",
    "version": "0.0.7",
    "project_urls": {
        "Homepage": "https://github.com/vivekkeshore/flask-dantic"
    },
    "split_keywords": [
        "sqlalchemy",
        "alchemy",
        "mysql",
        "postgres",
        "flask",
        "mssql",
        "sql",
        "sqlite",
        "serialize",
        "pydantic",
        "validate",
        "request",
        "orm",
        "serialization",
        "performance",
        "database",
        "relational"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "677b668fd4dbc93f4bebd0fa70d9261e29c950e98e37a92e8b5f2ed3303a6e9e",
                "md5": "618c708533a0c14cfc34d0d016bb2a07",
                "sha256": "799c9516bdb20ec22891c7f6fbd94ae715373311b317b8aa1fe57381f930432c"
            },
            "downloads": -1,
            "filename": "flask_dantic-0.0.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "618c708533a0c14cfc34d0d016bb2a07",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 14877,
            "upload_time": "2023-07-01T20:00:34",
            "upload_time_iso_8601": "2023-07-01T20:00:34.170741Z",
            "url": "https://files.pythonhosted.org/packages/67/7b/668fd4dbc93f4bebd0fa70d9261e29c950e98e37a92e8b5f2ed3303a6e9e/flask_dantic-0.0.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "574f4643120ae88bb9b0aa0e226905644a33113b1e1b96f316b376eec9104f54",
                "md5": "88664fe0eeadee9fad6171f672ad88b0",
                "sha256": "7a33654b2d09217fea03cf3959e599ad132a0f9b800c80a888a16f8ce1b3b1ba"
            },
            "downloads": -1,
            "filename": "flask-dantic-0.0.7.tar.gz",
            "has_sig": false,
            "md5_digest": "88664fe0eeadee9fad6171f672ad88b0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 14283,
            "upload_time": "2023-07-01T20:00:35",
            "upload_time_iso_8601": "2023-07-01T20:00:35.868836Z",
            "url": "https://files.pythonhosted.org/packages/57/4f/4643120ae88bb9b0aa0e226905644a33113b1e1b96f316b376eec9104f54/flask-dantic-0.0.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-01 20:00:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vivekkeshore",
    "github_project": "flask-dantic",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "pydantic",
            "specs": [
                [
                    "==",
                    "1.10.9"
                ]
            ]
        },
        {
            "name": "pytest",
            "specs": [
                [
                    "~=",
                    "6.2.3"
                ]
            ]
        },
        {
            "name": "sqlalchemy",
            "specs": [
                [
                    "~=",
                    "1.4.15"
                ]
            ]
        },
        {
            "name": "setuptools",
            "specs": [
                [
                    "~=",
                    "52.0.0"
                ]
            ]
        },
        {
            "name": "flask",
            "specs": [
                [
                    "~=",
                    "1.1.2"
                ]
            ]
        },
        {
            "name": "werkzeug",
            "specs": [
                [
                    "~=",
                    "1.0.1"
                ]
            ]
        }
    ],
    "lcname": "flask-dantic"
}
        
Elapsed time: 0.11148s