sarif-pydantic An implementation of the SARIF (Static Analysis Results Interchange Format) format using Pydantic. Overview This library provides Pydantic models for working with the SARIF specification (version 2.1.0). It enables Python developers to: Create, validate, and manipulate SARIF data Parse existing SARIF files into typed Python objects Export SARIF data to JSON with proper validation Installation bash pip install sarif-pydantic Usage Creating a SARIF Log ```python from sarif_pydantic import ( ArtifactLocation, Invocation, Level, Location, Message, PhysicalLocation, Region, Result, Run, Sarif, Tool, ToolDriver ) Create a tool driver tool_driver = ToolDriver( name="Example Analyzer", version="1.0.0", ) Create a tool with the driver tool = Tool(driver=tool_driver) Create a physical location physical_location = PhysicalLocation( artifact_location=ArtifactLocation( uri="src/example.py", ), region=Region( start_line=42, start_column=5, end_line=42, end_column=32, ), ) Create a result result = Result( rule_id="EX001", level=Level.WARNING, message=Message( text="Example warning message", ), locations=[Location( physical_location=physical_location, )], ) Create a SARIF log sarif_log = Sarif( version="2.1.0", runs=[Run( tool=tool, invocations=[Invocation( execution_successful=True, )], results=[result], )], ) Export to JSON sarif_json = sarif_log.model_dump_json(indent=2, exclude_none=True) print(sarif_json) ``` Loading a SARIF Log from JSON ```python import json from sarif_pydantic import Sarif Load from a file with open("example.sarif", "r") as f: sarif_data = json.load(f) Parse into a Sarif object sarif_log = Sarif.model_validate(sarif_data) Access data via typed objects for run in sarif_log.runs: for result in run.results or []: print(f"Rule: {result.rule_id}, Level: {result.level}") print(f"Message: {result.message.text}") ``` SARIF Specification This implementation follows the SARIF 2.1.0 specification. License [LICENSE]
pypi package. Binary
Latest version: 0.5.3 Released: 2025-04-11
============== pydantic-panel ============== pydantic-panel makes it easy to auto-generate UI elements from Pydantic models. .. image:: https://img.shields.io/pypi/v/pydantic_panel.svg :target: https://pypi.python.org/pypi/pydantic_panel :alt: Pypi package version .. image:: https://img.shields.io/badge/Python-3.7%2B-blue&style=flat :target: https://pypi.org/project/streamlit-pydantic/ :alt: Python version .. image:: https://img.shields.io/travis/jmosbacher/pydantic_panel.svg :target: https://travis-ci.com/jmosbacher/pydantic_panel :alt: Build Status .. image:: https://readthedocs.org/projects/pydantic-panel/badge/?version=latest :target: https://pydantic-panel.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://img.shields.io/badge/License-MIT-green.svg :target: https://github.com/jmosbacher/pydantic-panel/blob/master/LICENSE :alt: MIT License Getting Started | Documentation | Support_ pydantic-panel makes it easy to auto-generate UI elements from Pydantic models and any other Python object. The UI elements can be used in your Jupyter Notebook and in your Panel data app. .. image:: images/pydantic-panel-simple.png :width: 700 :align: center This project is at an early stage and potentially contains bugs. You might also see api changes, USE AT YOUR OWN RISK. I will continue to add support for more types as I need them. Feel free to open issues with feature requests or better yet PRs with implementations. Getting Started Step 1 - Install Requirements: Python 3.7+. .. code-block:: pip install pydantic-panel Step 2 - Import pydantic_panel and add your models to layouts! .. code-block:: python import pydantic class SomeModel(pydantic.BaseModel): name: str value: float model = SomeModel(name="meaning", value=42) import panel as pn import pydantic_panel pn.extension() widget = pn.panel(model) layout = pn.Column(widget, widget.json) layout.servable() Now you can edit your model: .. image:: images/simple_model_example.png :width: 400 How it works If you import pydantic_panel, it will register the widget automatically using the panel.BasePane.applies interface. After importing, calling panel.panel(model) will return a panel.CompositeWidget whos value is the model. When you change one of the sub-widget values, the new value is validated/coerced using the corresponding pydantic field and if it passes validation/coercion the new value is set on the model itself. By default this is a one-way sync, if the model field values are changed via code, it does not sync the widgets. If you want biderectional sync, you can pass bidirectional = True to the widget constructor, this will patch the model to sync changes to the widgets but this may break without warning if pydantic change the internals of their __setattr__ method. Customizing Behavior You can add or change the widgets used for a given type by hooking into the dispatch mechanism (we use plum-dispatch). This can be used to override the widget used for a supported type or to add support for a new type. .. code-block:: python from pydantic_panel import infer_widget from pydantic import FieldInfo from typing import Optional # precedence > 0 will ensure this function will be called # instead of the default which has precedence = 0 @infer_widget.dispatch(precedence=1) def infer_widget(value: MY_TYPE, field: Optional[FieldInfo = None, **kwargs): # extract relavent info from the pydantic field info here. # return your favorite widget return MY_FAVORITE_WIDGET(value=value, **kwargs) Supported types int float str list tuple dict datetime.datetime BaseModel List[BaseModel] pandas.Interval numpy.ndarray FAQ Q: Why did you decide to use CompositWidget instead of Pane like Param uses? A: Nested models. This is a recursive problem, so I was looking for a recursive solution. By using a Widget to display models, all fields are treated equally. A field of type BaseModel is edited with a widget that has a .value attribute just like any other field and therefore requires no special treatment. When the parent collects the values of its children it just reads the widget.value attribute and does not need to check whether the value is nested or not. At every level of the recursion the widget only has to care about the fields on its model class and watch only the .value attribute of its children widgets for changes. Features TODO Support & Feedback +---------------------+------------------------------------------------+ | Type | Channel | +=====================+================================================+ | 🐛 Bugs + |BugImage| | +---------------------+------------------------------------------------+ | 🎁 Features + |FeatureImage| | +---------------------+------------------------------------------------+ | ❓ Questions + |QuestionImage| | +---------------------+------------------------------------------------+ Credits This package was created with Cookiecutter_ and the briggySmalls/cookiecutter-pypackage_ project template. .. Cookiecutter: https://github.com/audreyr/cookiecutter .. briggySmalls/cookiecutter-pypackage: https://github.com/briggySmalls/cookiecutter-pypackage .. _Pydantic: https://github.com/samuelcolvin/pydantic/ .. _Panel: https://github.com/holoviz/panel .. _Getting Started: #getting-started .. _Documentation: https://pydantic-panel.readthedocs.io .. _Support: #support--feedback .. |BugImage| image:: https://img.shields.io/github/issues/jmosbacher/pydantic-panel/bug.svg?label=bug :target: https://github.com/jmosbacher/pydantic-panel/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3Abug+sort%3Areactions-%2B1-desc+ .. |FeatureImage| image:: https://img.shields.io/github/issues/jmosbacher/pydantic-panel/feature.svg?label=feature%20request :target: https://github.com/jmosbacher/pydantic-panel/issues?q=is%3Aopen+is%3Aissue+label%3Afeature+sort%3Areactions-%2B1-desc .. |QuestionImage| image:: https://img.shields.io/github/issues/jmosbacher/pydantic-panel/support.svg?label=support%20request :target: https://github.com/jmosbacher/pydantic-panel/issues?q=is%3Aopen+is%3Aissue+label%3Asupport+sort%3Areactions-%2B1-desc
Latest version: 0.2.0 Released: 2024-02-13
stapi-pydantic Pydantic models for the Satellite Tasking API (STAPI) specification. [!NOTE] This repository intentionally has no input/output (IO) functionality. For making requests to a STAPI API, use pystapi-client.
pypi package. Binary
Latest version: 0.0.3 Released: 2025-04-25
PySarif This is a simple pydantic model for the SARIF format, generated with datamodel-codegen. Installation bash pip install pysarif Usage StaticAnalysisResultsFormatSarifVersion210JsonSchema is likely the class that you'll be referencing the most. Example ```python from pydantic_sarif.model import StaticAnalysisResultsFormatSarifVersion210JsonSchema as Report example_json = """ """ report: Report = Report.parse_raw(example_json) assert report.version == "2.1.0" ```
pypi package. Binary
Latest version: 0.1.1 Released: 2023-08-15
Pydantic forms A Python package that lets you add smart forms to FastAPI and Flask. Forms will respond with a JSON scheme that contains all info needed in a React frontend with uniforms to render the forms and handle all validation tasks. Forms can also consist out of a wizard, so you can create complex form flows consisting out of multiple consecutive forms. The forms and the validation logic are defined by using Pydantic models. Documentation regarding the usage of Forms can be found here Installation (Development standalone) Install the project and its dependencies to develop on the code. Step 1 - install flit: shell python3 -m venv venv source venv/bin/activate pip install flit Step 2 - install the development code: shell flit install --deps develop --symlink --python venv/bin/python !!! danger Make sure to use the flit binary that is installed in your environment. You can check the correct path by running shell which flit To be sure that the packages will be installed against the correct venv you can also prepend the python interpreter that you want to use: shell flit install --deps develop --symlink --python venv/bin/python Running tests Run the unit-test suite to verify a correct setup. Step 2 - Run tests shell pytest tests/unit_tests or with xdist: shell pytest -n auto tests/unit_tests If you do not encounter any failures in the test, you should be able to develop features in the pydantic-forms. Installation (Development symlinked into project that use pydantic-forms) If you are working on a project that already uses the pydantic-forms and you want to test your new form features against it, you can use some flit magic to symlink the dev version of the forms to your project. It will automatically replace the pypi dep with a symlink to the development version of the core and update/downgrade all required packages in your own project. Step 1 - install flit: shell python - m venv venv source venv/bin/activate pip install flit Step 2 - symlink pydantic-forms to your own project shell flit install --deps develop --symlink --python /path/to/a/project/venv/bin/python Increasing the version number for a (pre) release. When your PR is accepted you will get a version number. You can do the necessary change with a clean, e.g. every change committed, branch: shell bumpversion patch --new-version 0.0.1 Note: specifying it like this, instead of relying on bumpversion itself to increase the version, allows you to set a "RC1" version if needed. Debugging Form behaviour If you want/need the traceback of pydantic in a Form response you can add an env variable: LOG_LEVEL_PYDANTIC_FORMS=DEBUG This will add the traceback to the JSONResponse. If the loglevel is set to DEBUG the library will also add the traceback to the logger.
Latest version: 2.0.0 Released: 2025-04-09
pydantic-sweep pydantic_sweep is a library to programmatically, safely and flexibly define complex parameter sweeps over pydantic models in Python. Highlights: - Specify parameter sweeps in Python - Flexibility: specify complex parameter combinations by chaining simple functional operations - Safety checks for parameter combinations (get meaningful errors early) - pydantic field validation For example, the following code will instantiate models with (x=5, sub=Sub1(s=1) and (x=6, sub=Sub1(s=2) and try each of those with seed values of seed=43 and seed=44, leading to four different configurations: ```python import pydantic_sweep as ps class Sub1(ps.BaseModel): s: int = 5 class Sub2(ps.BaseModel): y: str = "hi" class Model(ps.BaseModel): seed: int = 42 x: int = 5 sub: Sub1 | Sub2 We want to test across two seeds configs = ps.config_product( ps.field("seed", [43, 44]), # And two specific Sub1 and x combinations ps.config_zip( ps.field("x", [ps.DefaultValue, 6]), ps.field("sub.s", [1, 2]), ) ) This includes safety checks that Sub1 / Sub2 are uniquely specified models = ps.initialize(Model, configs) The code above is equivalent to models_manual = [ Model(seed=43, sub=Sub1(s=1)), Model(seed=43, x=6, sub=Sub1(s=2)), Model(seed=44, sub=Sub1(s=1)), Model(seed=44, x=6, sub=Sub1(s=2)), ] assert models == models_manual We can also check that we didn't accidentally duplicate a setting ps.check_unique(models) ``` While in this toy example, manually specifying the combinations may still be viable, the library allows infinitely combining different configs and sub-models, making it a powerful tool for large-scale experiment definition. To learn mode about the capabilities of the library please visit the documentation page. Installation You can install the library by checking out the repo and running bash pip install 'pydantic-sweep' License The main code-base is licensed under MPL-2.0 a weak copy-left license that allows commercial use. See the license file for the exact clauses and this FAQ for a high-level description. An exception from this are the documentation in the docs and example folders as well as this README file, which are licensed under the 0BSD: a highly permissive license that does not require attribution. That way, you are free to copy & paste example code into your use-case. See here for a high-level description.
Latest version: 0.3.3 Released: 2025-02-23
Pydantic-fetch Extension of pydantic.BaseModel which supports sending and parsing from HTTP endpoints. Description BaseModel is extended with two class functions: fetch to recieve a json payload from an endpoint and validate it as the pydantic model submit to send a pydantic model to an endpoint as a json payload. Usage ```python3 from pydantic_fetch import BaseModel class User(BaseModel): id: str name: str def send_user(endpoint, id: str, name: str): user = User(id=id, name=name) user.submit(endpoint) def get_user(endpoint): user = User.fetch(endpoint) ```
Latest version: 0.0.3 Released: 2022-10-09
pydantic-apply Installation Just use pip install pydantic-apply to install the library. Note: pydantic-apply is compatible with pydantic version 2.x on Python 3.9, 3.10, 3.11, 3.12 and 3.13. This is also ensured running all tests on all those versions using tox. About With pydantic-apply you can apply changes to your pydantic models by using the ApplyModelMixin it provides: ```python import pydantic from pydantic_apply import ApplyModelMixin class Something(ApplyModelMixin, pydantic.BaseModel): name: str age: int obj = Something(name='John Doe', age=42) obj.model_apply({ "age": 43, }) assert obj.age == 43 ``` As the apply data you may pass any dictionary or other pydanic object as you wish. pydantic objects will be converted to dict's when being applied - but will only use fields that where explicitly set on the model instance. Also note that .apply() will ignore all fields not present in the model, like the model constructor would. Nested models pydantic-apply will also know how to apply changes to nested models. If those models are by themself subclasses of ApplyModelMixin it will call apply() on those fields as well. Otherwise the whole attribute will be replaced. Apply changes when using validate_assignment When your models have validate_assignment enabled it may become tricky to apply changes to the model. This is due to the fact that you only can assign fields once at a time. But with validate_assignment enabled this means each field assignment will trigger its own validation and this validation might fail as the model state is not completely changes and thus in a "broken" intermediate state. pydantic-apply will take care of this issue and disable the validation for each assignment while applying the changes. It will also ensure the resulting object will still pass the validation, so you don't have to care about this case at all. Contributing If you want to contribute to this project, feel free to just fork the project, create a dev branch in your fork and then create a pull request (PR). If you are unsure about whether your changes really suit the project please create an issue first, to talk about this.
Latest version: 0.7.1 Released: 2025-05-05
Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Pallets Community Ecosystem [!IMPORTANT]\ This project is part of the Pallets Community Ecosystem. Pallets is the open source organization that maintains Flask; Pallets-Eco enables community maintenance of Flask extensions. If you are interested in helping maintain this project, please reach out on the Pallets Discord server. Installation python3 -m pip install Flask-Pydantic Basics URL query and body parameters validate decorator validates query, body and form-data request parameters and makes them accessible two ways: Using validate arguments, via flask's request variable | parameter type | request attribute name | |:------------------:|:----------------------------:| | query | query_params | | body | body_params | | form | form_params | Using the decorated function argument parameters type hints URL path parameter If you use annotated path URL path parameters as follows ```python @app.route("/users/", methods=["GET"]) @validate() def get_user(user_id: str): pass `` flask_pydantic will parse and validateuser_id` variable in the same manner as for body and query parameters. Additional validate arguments Success response status code can be modified via on_success_status parameter of validate decorator. response_many parameter set to True enables serialization of multiple models (route function should therefore return iterable of models). request_body_many parameter set to False analogically enables serialization of multiple models inside of the root level of request body. If the request body doesn't contain an array of objects 400 response is returned, get_json_params - parameters to be passed to flask.Request.get_json function If validation fails, 400 response is returned with failure explanation. For more details see in-code docstring or example app. Usage Example 1: Query parameters only Simply use validate decorator on route function. :exclamation: Be aware that @app.route decorator must precede @validate (i. e. @validate must be closer to the function declaration). ```python from typing import Optional from flask import Flask, request from pydantic import BaseModel from flask_pydantic import validate app = Flask("flask_pydantic_app") class QueryModel(BaseModel): age: int class ResponseModel(BaseModel): id: int age: int name: str nickname: Optional[str] = None Example 1: query parameters only @app.route("/", methods=["GET"]) @validate() def get(query: QueryModel): age = query.age return ResponseModel( age=age, id=0, name="abc", nickname="123" ) ``` See the full example app here age query parameter is a required int curl --location --request GET 'http://127.0.0.1:5000/' if none is provided the response contains: json { "validation_error": { "query_params": [ { "loc": ["age"], "msg": "field required", "type": "value_error.missing" } ] } } for incompatible type (e. g. string /?age=not_a_number) curl --location --request GET 'http://127.0.0.1:5000/?age=abc' json { "validation_error": { "query_params": [ { "loc": ["age"], "msg": "value is not a valid integer", "type": "type_error.integer" } ] } } likewise for body parameters example call with valid parameters: curl --location --request GET 'http://127.0.0.1:5000/?age=20' -> {"id": 0, "age": 20, "name": "abc", "nickname": "123"} Example 2: URL path parameter python @app.route("/character//", methods=["GET"]) @validate() def get_character(character_id: int): characters = [ ResponseModel(id=1, age=95, name="Geralt", nickname="White Wolf"), ResponseModel(id=2, age=45, name="Triss Merigold", nickname="sorceress"), ResponseModel(id=3, age=42, name="Julian Alfred Pankratz", nickname="Jaskier"), ResponseModel(id=4, age=101, name="Yennefer", nickname="Yenn"), ] try: return characters[character_id] except IndexError: return {"error": "Not found"}, 400 Example 3: Request body only ```python class RequestBodyModel(BaseModel): name: str nickname: Optional[str] = None Example2: request body only @app.route("/", methods=["POST"]) @validate() def post(body: RequestBodyModel): name = body.name nickname = body.nickname return ResponseModel( name=name, nickname=nickname,id=0, age=1000 ) ``` See the full example app here Example 4: BOTH query paramaters and request body ```python Example 3: both query paramters and request body @app.route("/both", methods=["POST"]) @validate() def get_and_post(body: RequestBodyModel, query: QueryModel): name = body.name # From request body nickname = body.nickname # From request body age = query.age # from query parameters return ResponseModel( age=age, name=name, nickname=nickname, id=0 ) ``` See the full example app here Example 5: Request form-data only ```python class RequestFormDataModel(BaseModel): name: str nickname: Optional[str] = None Example2: request body only @app.route("/", methods=["POST"]) @validate() def post(form: RequestFormDataModel): name = form.name nickname = form.nickname return ResponseModel( name=name, nickname=nickname,id=0, age=1000 ) ``` See the full example app here Modify response status code The default success status code is 200. It can be modified in two ways in return statement ```python necessary imports, app and models definition ... @app.route("/", methods=["POST"]) @validate(body=BodyModel, query=QueryModel) def post(): return ResponseModel( id=id_, age=request.query_params.age, name=request.body_params.name, nickname=request.body_params.nickname, ), 201 ``` in validate decorator python @app.route("/", methods=["POST"]) @validate(body=BodyModel, query=QueryModel, on_success_status=201) def post(): ... Status code in case of validation error can be modified using FLASK_PYDANTIC_VALIDATION_ERROR_STATUS_CODE flask configuration variable. Using the decorated function kwargs Instead of passing body and query to validate, it is possible to directly defined them by using type hinting in the decorated function. ```python necessary imports, app and models definition ... @app.route("/", methods=["POST"]) @validate() def post(body: BodyModel, query: QueryModel): return ResponseModel( id=id_, age=query.age, name=body.name, nickname=body.nickname, ) ``` This way, the parsed data will be directly available in body and query. Furthermore, your IDE will be able to correctly type them. Model aliases Pydantic's alias feature is natively supported for query and body models. To use aliases in response modify response model ```python def modify_key(text: str) -> str: # do whatever you want with model keys return text class MyModel(BaseModel): ... model_config = ConfigDict( alias_generator=modify_key, populate_by_name=True ) ``` and set response_by_alias=True in validate decorator python @app.route(...) @validate(response_by_alias=True) def my_route(): ... return MyModel(...) Example app For more complete examples see example application. Configuration The behaviour can be configured using flask's application config FLASK_PYDANTIC_VALIDATION_ERROR_STATUS_CODE - response status code after validation error (defaults to 400) Additionally, you can set FLASK_PYDANTIC_VALIDATION_ERROR_RAISE to True to cause flask_pydantic.ValidationError to be raised with either body_params, form_params, path_params, or query_params set as a list of error dictionaries. You can use flask.Flask.register_error_handler to catch that exception and fully customize the output response for a validation error. Contributing Feature requests and pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. clone repository bash git clone https://github.com/pallets-eco/flask_pydantic.git cd flask_pydantic create virtual environment and activate it bash python3 -m venv venv source venv/bin/activate install development requirements bash python3 -m pip install -r requirements/test.txt checkout new branch and make your desired changes (don't forget to update tests) bash git checkout -b make sure your code style is compliant with Ruff. Your can check these errors and automatically correct some of them with ruff check --select I --fix . run tests and check code format bash python3 -m pytest --ruff --ruff-format push your changes and create a pull request to master branch TODOs: header request parameters cookie request parameters
Latest version: 0.13.1 Released: 2025-04-23