Name | flask-typed-routes JSON |
Version |
0.0.8
JSON |
| download |
home_page | None |
Summary | Flask extension designed to effortlessly validate requests with Pydantic based on standard Python type hints. |
upload_time | 2024-12-12 13:00:50 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.10 |
license | MIT License Copyright (c) 2024 Rolando Morales Perez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
python
flask
pydantic
validation
extension
typing
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
[![CI](https://github.com/rmoralespp/flask_typed_routes/workflows/CI/badge.svg)](https://github.com/rmoralespp/flask_typed_routes/actions?query=event%3Arelease+workflow%3ACI)
[![pypi](https://img.shields.io/pypi/v/flask_typed_routes.svg)](https://pypi.python.org/pypi/flask_typed_routes)
[![codecov](https://codecov.io/gh/rmoralespp/flask_typed_routes/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rmoralespp/flask_typed_routes)
[![license](https://img.shields.io/github/license/rmoralespp/flask_typed_routes.svg)](https://github.com/rmoralespp/flask_typed_routes/blob/main/LICENSE)
[![Downloads](https://pepy.tech/badge/flask_typed_routes)](https://pepy.tech/project/flask_typed_routes)
## About
**flask_typed_routes** is a `Flask` extension designed to effortlessly validate requests with `Pydantic` based on standard Python type hints.
**Documentation**: https://rmoralespp.github.io/flask_typed_routes/
## Features
- 🎯 **Type Safety:** Automatically validates requests using Python type hints.
- 🔌 **Easy Integration:** Simple extension for validating Flask routes.
- ⚠️ **Error Handling:** Clear and automatic responses for validation failures.
- ✨ **Autocomplete:** Editor integration with comprehensive suggestions.
- ⚙️ **Validation Modes:** Supports automatic validation for all routes and manual validation for specific routes using decorators.
## Requirements
- Python 3.10+
- Pydantic 2.0+
- Flask
## Installation
To install **flask_typed_routes** using `pip`, run the following command:
```bash
pip install flask_typed_routes
```
## Getting Started
This tool offers comprehensive validation for various types of request parameters,
including **Path, Query, Body, Header, and Cookie** parameters.
Example of a simple Flask application using `flask_typed_routes`:
Create a file `items.py` with:
```python
import typing as t
import annotated_types as at
import flask
import flask_typed_routes as ftr
import pydantic
app = flask.Flask(__name__)
ftr.FlaskTypedRoutes(app)
Skip = pydantic.NonNegativeInt # custom Pydantic type
Limit = t.Annotated[int, at.Ge(1), at.Le(100)] # custom Annotated type
@app.get('/items/<user>/')
def get_items(user: str, skip: Skip = 0, limit: Limit = 10):
# Parameters not included in the "path" are automatically treated as "query" parameters.
data = {
'user': user,
'skip': skip,
'limit': limit,
}
return flask.jsonify(data)
```
**Run the server with:**
```bash
flask --app items run --debug
```
Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=20`
You will see the JSON response as:
```json
{
"limit": 10,
"skip": 20,
"user": "myuser"
}
```
**Validation:** Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=abc`
You will see the JSON response with the error details because the `skip` parameter is not an integer:
```json
{
"errors": [
{
"input": "abc",
"loc": [
"query",
"skip"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"type": "int_parsing",
"url": "https://errors.pydantic.dev/2.9/v/int_parsing"
}
]
}
```
### Example with Pydantic Models
You can also use Pydantic models to validate request data in Flask routes.
Now let's update the `items.py` file with:
```python
import pydantic
import flask
import flask_typed_routes as ftr
app = flask.Flask(__name__)
ftr.FlaskTypedRoutes(app)
class Item(pydantic.BaseModel):
name: str
description: str = None
price: float
@app.post('/items/')
def create_item(item: Item):
return flask.jsonify(item.model_dump())
@app.put('/items/<item_id>/')
def update_item(item_id: int, item: Item):
return flask.jsonify({'item_id': item_id, **item.model_dump()})
```
### Using Flask Blueprints
You can also use `flask_typed_routes` with Flask Blueprints.
Now let's update the `items.py` file with:
```python
import flask
import flask_typed_routes as ftr
app = flask.Flask(__name__)
ftr.FlaskTypedRoutes(app)
blp = flask.Blueprint('items', __name__, url_prefix='/v2')
@blp.get('/items/')
def get_items_v2(skip: int = 0, limit: int = 10, country: str = 'US'):
data = {'skip': skip, 'limit': limit, 'country': country}
return flask.jsonify(data)
app.register_blueprint(blp)
```
### Using Flask Class-Based Views
You can also use `flask_typed_routes` with Flask Class-Based Views.
Now let's update the `items.py` file with:
```python
import flask
import flask.views
import flask_typed_routes as ftr
app = flask.Flask(__name__)
ftr.FlaskTypedRoutes(app)
class UserProducts(flask.views.View):
def dispatch_request(self, user: str, skip: int = 0, limit: int = 10):
data = {'user': user, 'skip': skip, 'limit': limit}
return flask.jsonify(data)
class UserOrders(flask.views.MethodView):
def get(self, user: str, skip: int = 0, limit: int = 10):
data = {'user': user, 'skip': skip, 'limit': limit}
return flask.jsonify(data)
app.add_url_rule('/products/<user>/all/', view_func=UserProducts.as_view('user_products'))
app.add_url_rule('/orders/<user>/all/', view_func=UserOrders.as_view('user_orders'))
```
## Documentation
For more detailed information and usage examples, refer to the
project [documentation](https://rmoralespp.github.io/flask_typed_routes/)
## Development
To contribute to the project, you can run the following commands for testing and documentation:
### Running Unit Tests
Install the development dependencies and run the tests:
```
(env)$ pip install -r requirements-dev.txt # Skip if already installed
(env)$ python -m pytest tests/
(env)$ python -m pytest --cov # Run tests with coverage
```
### Building the Documentation
To build the documentation locally, use the following commands:
```
(env)$ pip install -r requirements-doc.txt # Skip if already installed
(env)$ mkdocs serve # Start live-reloading docs server
(env)$ mkdocs build # Build the documentation site
```
## License
This project is licensed under the [MIT license](LICENSE).
Raw data
{
"_id": null,
"home_page": null,
"name": "flask-typed-routes",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "python, flask, pydantic, validation, extension, typing",
"author": null,
"author_email": "rmoralespp <rmoralespp@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/00/aa/c01b19694b53346b72f8fae2e8882ee4cd4080f187bfe158e47133362bd1/flask_typed_routes-0.0.8.tar.gz",
"platform": null,
"description": "[![CI](https://github.com/rmoralespp/flask_typed_routes/workflows/CI/badge.svg)](https://github.com/rmoralespp/flask_typed_routes/actions?query=event%3Arelease+workflow%3ACI)\n[![pypi](https://img.shields.io/pypi/v/flask_typed_routes.svg)](https://pypi.python.org/pypi/flask_typed_routes)\n[![codecov](https://codecov.io/gh/rmoralespp/flask_typed_routes/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rmoralespp/flask_typed_routes)\n[![license](https://img.shields.io/github/license/rmoralespp/flask_typed_routes.svg)](https://github.com/rmoralespp/flask_typed_routes/blob/main/LICENSE)\n[![Downloads](https://pepy.tech/badge/flask_typed_routes)](https://pepy.tech/project/flask_typed_routes)\n\n## About\n\n**flask_typed_routes** is a `Flask` extension designed to effortlessly validate requests with `Pydantic` based on standard Python type hints.\n\n**Documentation**: https://rmoralespp.github.io/flask_typed_routes/\n\n## Features\n\n- \ud83c\udfaf **Type Safety:** Automatically validates requests using Python type hints.\n- \ud83d\udd0c **Easy Integration:** Simple extension for validating Flask routes.\n- \u26a0\ufe0f **Error Handling:** Clear and automatic responses for validation failures.\n- \u2728 **Autocomplete:** Editor integration with comprehensive suggestions.\n- \u2699\ufe0f **Validation Modes:** Supports automatic validation for all routes and manual validation for specific routes using decorators.\n\n\n## Requirements\n\n- Python 3.10+\n- Pydantic 2.0+\n- Flask\n\n## Installation\n\nTo install **flask_typed_routes** using `pip`, run the following command:\n\n```bash\npip install flask_typed_routes\n```\n\n## Getting Started\n\nThis tool offers comprehensive validation for various types of request parameters,\nincluding **Path, Query, Body, Header, and Cookie** parameters.\n\nExample of a simple Flask application using `flask_typed_routes`:\n\nCreate a file `items.py` with:\n\n```python\nimport typing as t\n\nimport annotated_types as at\nimport flask\nimport flask_typed_routes as ftr\nimport pydantic\n\napp = flask.Flask(__name__)\nftr.FlaskTypedRoutes(app)\n\nSkip = pydantic.NonNegativeInt # custom Pydantic type\nLimit = t.Annotated[int, at.Ge(1), at.Le(100)] # custom Annotated type\n\n@app.get('/items/<user>/')\ndef get_items(user: str, skip: Skip = 0, limit: Limit = 10):\n # Parameters not included in the \"path\" are automatically treated as \"query\" parameters.\n data = {\n 'user': user,\n 'skip': skip,\n 'limit': limit,\n }\n return flask.jsonify(data)\n```\n\n**Run the server with:**\n\n```bash\nflask --app items run --debug\n```\n\nOpen your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=20`\nYou will see the JSON response as:\n\n```json\n{\n \"limit\": 10,\n \"skip\": 20,\n \"user\": \"myuser\"\n}\n```\n\n**Validation:** Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=abc`\nYou will see the JSON response with the error details because the `skip` parameter is not an integer:\n\n```json\n{\n \"errors\": [\n {\n \"input\": \"abc\",\n \"loc\": [\n \"query\",\n \"skip\"\n ],\n \"msg\": \"Input should be a valid integer, unable to parse string as an integer\",\n \"type\": \"int_parsing\",\n \"url\": \"https://errors.pydantic.dev/2.9/v/int_parsing\"\n }\n ]\n}\n```\n\n### Example with Pydantic Models\n\nYou can also use Pydantic models to validate request data in Flask routes.\nNow let's update the `items.py` file with:\n\n```python\nimport pydantic\nimport flask\nimport flask_typed_routes as ftr\n\napp = flask.Flask(__name__)\nftr.FlaskTypedRoutes(app)\n\n\nclass Item(pydantic.BaseModel):\n name: str\n description: str = None\n price: float\n\n\n@app.post('/items/')\ndef create_item(item: Item):\n return flask.jsonify(item.model_dump())\n\n\n@app.put('/items/<item_id>/')\ndef update_item(item_id: int, item: Item):\n return flask.jsonify({'item_id': item_id, **item.model_dump()})\n```\n\n### Using Flask Blueprints\n\nYou can also use `flask_typed_routes` with Flask Blueprints.\n\nNow let's update the `items.py` file with:\n\n```python\nimport flask\nimport flask_typed_routes as ftr\n\napp = flask.Flask(__name__)\nftr.FlaskTypedRoutes(app)\nblp = flask.Blueprint('items', __name__, url_prefix='/v2')\n\n\n@blp.get('/items/')\ndef get_items_v2(skip: int = 0, limit: int = 10, country: str = 'US'):\n data = {'skip': skip, 'limit': limit, 'country': country}\n return flask.jsonify(data)\n\n\napp.register_blueprint(blp)\n```\n\n### Using Flask Class-Based Views\n\nYou can also use `flask_typed_routes` with Flask Class-Based Views.\n\nNow let's update the `items.py` file with:\n\n```python\nimport flask\nimport flask.views\nimport flask_typed_routes as ftr\n\napp = flask.Flask(__name__)\nftr.FlaskTypedRoutes(app)\n\n\nclass UserProducts(flask.views.View):\n\n def dispatch_request(self, user: str, skip: int = 0, limit: int = 10):\n data = {'user': user, 'skip': skip, 'limit': limit}\n return flask.jsonify(data)\n\n\nclass UserOrders(flask.views.MethodView):\n \n def get(self, user: str, skip: int = 0, limit: int = 10):\n data = {'user': user, 'skip': skip, 'limit': limit}\n return flask.jsonify(data)\n\n \napp.add_url_rule('/products/<user>/all/', view_func=UserProducts.as_view('user_products'))\napp.add_url_rule('/orders/<user>/all/', view_func=UserOrders.as_view('user_orders'))\n```\n\n## Documentation\n\nFor more detailed information and usage examples, refer to the\nproject [documentation](https://rmoralespp.github.io/flask_typed_routes/)\n\n## Development\n\nTo contribute to the project, you can run the following commands for testing and documentation:\n\n### Running Unit Tests\n\nInstall the development dependencies and run the tests:\n\n```\n(env)$ pip install -r requirements-dev.txt # Skip if already installed\n(env)$ python -m pytest tests/\n(env)$ python -m pytest --cov # Run tests with coverage\n```\n\n### Building the Documentation\n\nTo build the documentation locally, use the following commands:\n\n```\n(env)$ pip install -r requirements-doc.txt # Skip if already installed\n(env)$ mkdocs serve # Start live-reloading docs server\n(env)$ mkdocs build # Build the documentation site\n```\n\n## License\n\nThis project is licensed under the [MIT license](LICENSE).\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2024 Rolando Morales Perez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
"summary": "Flask extension designed to effortlessly validate requests with Pydantic based on standard Python type hints.",
"version": "0.0.8",
"project_urls": {
"Changelog": "https://github.com/rmoralespp/flask_typed_routes/blob/main/CHANGELOG.md",
"Documentation": "https://rmoralespp.github.io/flask_typed_routes/",
"Homepage": "https://github.com/rmoralespp/flask_typed_routes",
"Issues": "https://github.com/rmoralespp/flask_typed_routes/issues",
"Source": "https://github.com/rmoralespp/flask_typed_routes"
},
"split_keywords": [
"python",
" flask",
" pydantic",
" validation",
" extension",
" typing"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "ccd7f15296f2858fd158689e590b6a79e240cdcb7ce09234e8818706832824c7",
"md5": "8edff78208bb00b42354cf27da4e2933",
"sha256": "c63f948387a112cbe6b718e7734020b057b8c694116f3e5f2696c94188b10809"
},
"downloads": -1,
"filename": "flask_typed_routes-0.0.8-py3-none-any.whl",
"has_sig": false,
"md5_digest": "8edff78208bb00b42354cf27da4e2933",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 11568,
"upload_time": "2024-12-12T13:00:47",
"upload_time_iso_8601": "2024-12-12T13:00:47.747489Z",
"url": "https://files.pythonhosted.org/packages/cc/d7/f15296f2858fd158689e590b6a79e240cdcb7ce09234e8818706832824c7/flask_typed_routes-0.0.8-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "00aac01b19694b53346b72f8fae2e8882ee4cd4080f187bfe158e47133362bd1",
"md5": "58f10de38d1bb7ec99ee7280b153f406",
"sha256": "14eb486826a23421eaa3c8ec973f1989081855d1037c05bc1c021a1869044cbe"
},
"downloads": -1,
"filename": "flask_typed_routes-0.0.8.tar.gz",
"has_sig": false,
"md5_digest": "58f10de38d1bb7ec99ee7280b153f406",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 12477,
"upload_time": "2024-12-12T13:00:50",
"upload_time_iso_8601": "2024-12-12T13:00:50.349106Z",
"url": "https://files.pythonhosted.org/packages/00/aa/c01b19694b53346b72f8fae2e8882ee4cd4080f187bfe158e47133362bd1/flask_typed_routes-0.0.8.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-12 13:00:50",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "rmoralespp",
"github_project": "flask_typed_routes",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "flask-typed-routes"
}