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
Pydantic Mongo A Python library that offers an easy-to-use Repository pattern for MongoDB, supporting both synchronous and asynchronous operations. It simplifies working with databases by providing a clear interface for CRUD (Create, Read, Update, Delete) operations using Pydantic models. With built-in data validation and serialization from Pydantic, it helps manage your MongoDB data safely. Read the documentation Features Asynchronous and Synchronous support Pydantic models integration Type-safe MongoDB operations Cursor-based pagination Installation bash pip install pydantic-mongo Usage Examples Defining Models and Repository ```python from bson import ObjectId from pydantic import BaseModel from pydantic_mongo import AbstractRepository, PydanticObjectId from pymongo import MongoClient from typing import Optional, List Define your models class Foo(BaseModel): count: int size: float = None class Bar(BaseModel): apple: str = 'x' banana: str = 'y' class Spam(BaseModel): # PydanticObjectId is an alias to Annotated[ObjectId, ObjectIdAnnotation] id: Optional[PydanticObjectId] = None foo: Foo bars: List[Bar] Create a repository class SpamRepository(AbstractRepository[Spam]): class Meta: collection_name = 'spams' Connect to database client = MongoClient("mongodb://localhost:27017") database = client["example"] repo = SpamRepository(database) ``` Creating and Saving Documents ```python Create a new document spam = Spam(foo=Foo(count=1, size=1.0), bars=[Bar()]) Create a document with predefined ID spam_with_predefined_id = Spam( id=ObjectId("611827f2878b88b49ebb69fc"), foo=Foo(count=2, size=2.0), bars=[Bar()] ) Save a single document repo.save(spam) # spam.id is now set to an ObjectId Save multiple documents repo.save_many([spam, spam_with_predefined_id]) ``` Querying Documents ```python Find by ID result = repo.find_one_by_id(spam.id) Find by ID using string result = repo.find_one_by_id(ObjectId('611827f2878b88b49ebb69fc')) assert result.foo.count == 2 Find one by custom query result = repo.find_one_by({'foo.count': 1}) Find multiple documents by query results = repo.find_by({'foo.count': {'$gte': 1}}) ``` Pagination ```python Get first page edges = repo.paginate({'foo.count': {'$gte': 1}}, limit=10) Get next page using the last cursor more_edges = repo.paginate( {'foo.count': {'$gte': 1}}, limit=10, after=list(edges)[-1].cursor ) ``` Deleting Documents ```python Delete a document repo.delete(spam) Delete by ID repo.delete_by_id(ObjectId("...")) ``` Async Support For asynchronous applications, you can use AsyncAbstractRepository which provides the same functionality as AbstractRepository but with async/await support: ```python from pymongo import AsyncMongoClient from pydantic import BaseModel from pydantic_mongo import AsyncAbstractRepository class User(BaseModel): id: str name: str email: str class UserRepository(AsyncAbstractRepository[User]): class Meta: collection_name = 'users' Initialize database connection client = AsyncMongoClient('mongodb://localhost:27017') database = client["mydb"] Create repository instance user_repo = UserRepository(database) Example usage user = User(name='John Doe', email='john@example.com') await user_repo.save(user) user = await user_repo.find_one_by_id(user_id) ``` License MIT License
Latest version: 3.1.0 Released: 2025-04-18
.. |docs| image:: https://readthedocs.org/projects/pydantic-views/badge/?version=latest :alt: Documentation Status :target: https://pydantic-views.readthedocs.io/latest/?badge=latest .. |python-versions| image:: https://img.shields.io/pypi/pyversions/pydantic-views :alt: PyPI - Python Version .. |typed| image:: https://img.shields.io/pypi/types/pydantic-views :alt: PyPI - Types .. |license| image:: https://img.shields.io/pypi/l/pydantic-views :alt: PyPI - License .. |version| image:: https://img.shields.io/pypi/v/pydantic-views :alt: PyPI - Version |docs| |python-versions| |typed| |license| |version| .. start-doc ====================================== View for Pydantic models documentation ====================================== This package provides a simple way to create views from pydantic models. A view is another pydantic models with some of field of original model. So, for example, read only fields does not appears on Create or Update views. As rest service definition you could do: .. code-block:: python ExampleModelCreate = BuilderCreate().build_view(ExampleModel) ExampleModelCreateResult = BuilderCreateResult().build_view(ExampleModel) ExampleModelLoad = BuilderLoad().build_view(ExampleModel) ExampleModelUpdate = BuilderUpdate().build_view(ExampleModel) def create(input: ExampleModelCreate) -> ExampleModelCreateResult: ... def load(model_id: str) -> ExampleModelLoad: ... def update(model_id: str, input: ExampleModelUpdate) -> ExampleModelLoad: ... Features Unlimited views per model. Create view for referenced inner models. It is possible to set a view manually. Tested code. Full typed. Opensource. Installation Using pip: .. code-block:: bash pip install pydantic-views Using poetry_: .. code-block:: bash poetry add pydantic-views How to use When you define a pydantic model you must mark the access model for each field. It means you should use our annotations_ to define field typing. .. code-block:: python from typing import Annotated from pydantic import BaseModel, gt from pydantic_views import ReadOnly, ReadOnlyOnCreation, Hidden, AccessMode class ExampleModel(BaseModel): # No marked fields are treated like ReadAndWrite fields. field_str: str # Read only fields are removed on view for create and update views. field_read_only_str: ReadOnly[str] # Read only on creation fields are removed on view for create, update and load views. # But it is shown on create result view. field_api_secret: ReadOnlyOnCreation[str] # It is possible to set more than one access mode and to use annotation standard pattern. field_int: Annotated[int, AccessMode.READ_ONLY, AccessMode.WRITE_ONLY_ON_CREATION, gt(5)] # Hidden field do not appears in any view. field_hidden_int: Hidden[int] # Computed fields only appears on reading views. @computed_field def field_computed_field(self) -> int: return self.field_hidden_int * 5 So, in order to build a Load view it is so simple: .. code-block:: python from pydantic_views import BuilderLoad ExampleModelLoad = BuilderLoad().build_view(ExampleModel) It is equivalent to: .. code-block:: python from pydantic import gt from pydantic_views import View class ExampleModelLoad(View[ExampleModel]): field_str: str field_int: Annotated[int, gt(5)] field_computed_field: int In same way to build a Update view you must do: .. code-block:: python from pydantic_views import BuilderUpdate ExampleModelUpdate = BuilderUpdate().build_view(ExampleModel) It is equivalent to: .. code-block:: python from pydantic import PydanticUndefined from pydantic_views import View class ExampleModelUpdate(View[ExampleModel]): field_str: str = Field(default_factory=lambda: PydanticUndefined) As you can see, on Update view all fields has a default factory returning PydanticUndefined in order to make them optionals. And when an update view is applied to a given model, the fields that are not set (use default value) will not be applied to the model. .. code-block:: python original_model = ExampleModel( field_str="anything" field_read_only_str="anything" field_api_secret="anything" field_int=10 field_hidden_int=33 ) update = ExampleModelUpdate(field_str="new_data") updated_model = update.view_apply_to(original_model) assert isinstance(updated_model, ExampleModel) assert updated_model.field_str == "new_data" But if a field is not set on update view, the original value is kept. .. code-block:: python original_model = ExampleModel( field_str="anything" field_read_only_str="anything" field_api_secret="anything" field_int=10 field_hidden_int=33 ) update = ExampleModelUpdate() updated_model = update.view_apply_to(original_model) assert isinstance(updated_model, ExampleModel) assert updated_model.field_str == "anything"
Latest version: 0.1.0 Released: 2025-03-14
pydantic-kedro Advanced serialization for Pydantic models via Kedro and fsspec. This package implements custom Kedro "datasets" for both "pure" and "arbitrary" Pydantic models. You can also use it stand-alone, using Kedro just for serializing other object types. Please see the documentation for a tutorial and more examples. Usage with Kedro You can use the [PydanticAutoDataset][pydantic_kedro.PydanticAutoDataset] or any other dataset from pydantic-kedro within your Kedro catalog to save your Pydantic models: ```yaml conf/base/catalog.yml my_pydantic_model: type: pydantic_kedro.PydanticAutoDataset filepath: folder/my_model ``` Direct Dataset Usage This example works for "pure", JSON-safe Pydantic models via PydanticJsonDataset: ```python from pydantic import BaseModel from pydantic.v1 import BaseModel # Pydantic V2 from pydantic_kedro import PydanticJsonDataset class MyPureModel(BaseModel): """Your custom Pydantic model with JSON-safe fields.""" x: int y: str obj = MyPureModel(x=1, y="why?") Create an in-memory (temporary) file via fsspec and save it ds = PydanticJsonDataset("memory://temporary-file.json") ds.save(obj) We can re-load it from the same file read_obj = ds.load() assert read_obj.x == 1 ``` Standalone Usage You can also use pydantic-kedro as a generic saving and loading engine for Pydantic models: ```python from tempfile import TemporaryDirectory from pydantic.v1 import BaseModel from pydantic_kedro import load_model, save_model class MyModel(BaseModel): """My custom model.""" name: str We can use any fsspec URL, so we'll make a temporary folder with TemporaryDirectory() as tmpdir: save_model(MyModel(name="foo"), f"{tmpdir}/my_model") obj = load_model(f"{tmpdir}/my_model") assert obj.name == "foo" ```
Latest version: 0.8.0 Released: 2024-04-01
ed318-pydantic Pydantic models for ED-318. Description ed318-pydantic provides a suite of Pydantic models matching the data model specified in ED-318 Technical Specification fro Geographical Zones.
pypi package. Binary
Latest version: 0.2.1 Released: 2025-04-30
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
Purpose of the Package To translate from Pydantic models to Neo4j Graphs Getting Started Install the package bash pip install pydantic-neo4j Usage Import the package and models python from pydantic_neo4j import (PydanticNeo4j, RelationshipQueryModel, NodeModel, SequenceCriteriaNodeModel, SequenceCriteriaRelationshipModel, SequenceQueryModel, SequenceNodeModel) Initialize the class and get the utilities ```python pydantic_neo4j = PydanticNeo4j(username='neo4j', password='neo4j', uri='neo4j://localhost:7687) match_util = pydantic_neo4j.match_utilities create_util = pydantic_neo4j.create_utilities database_operations = pydantic_neo4j.database_operations ``` Create some Pydantic models ```python class Manufacturer(NodeModel): name: str class Design(NodeModel): color: str class Component(NodeModel): name: str class IsOrderable(RelationshipModel): pass class Produces(RelationshipModel): design_revision: int ``` Create the nodes and relationships. All relationships must have a start_node and end_node ```python relationships = [] manufacturer = Manufacturer(name="Acme") design = Design(color="red") produces = Produces(design_revision=3, start_node=manufacturer, end_node=design) + Add to listpython relationships.append(produces) + Create another relationship and add it to the listpython component = Component(component_type="widget") is_orderable = IsOrderable(start_node=design, end_node=component) relationships.append(is_orderable) ``` Add the nodes and relationships to the graph ```python await create_util.create_relationships(relationships=relationships) ```` Query the graph for a single node. Lets find a manufacturer ```python nodes = await match_util.node_query(node_name='Manufacturer') + Query the graph for multiple nodes. Lets find all nodes that are activepython nodes = await match_util.node_query(criteria={'active': True}) ``` Query the graph for a single relationship. Lets find a manufacturer that produces a red design This will be depreciated soon, use sequence query instead python query = RelationshipQueryModel( start_node_name="Manufacturer", start_criteria={}, end_node_name="Design", end_criteria={"color": "red"}, relationship_name="Produces", relationship_criteria={}) result = await match_util.match_relationship(query=query) Query the graph for multiple relationships. Lets find all manufacturers that make a widget component This uses a sequence, which is a series of relationships. Similar to Neo4j Path ```python sequence_query = SequenceQueryModel() sequence_query.node_sequence.append(SequenceCriteriaNodeModel(name='Manufacturer')) sequence_query.relationship_sequence.append(SequenceCriteriaRelationshipModel()) # a relationship with no criteria sequence_query.node_sequence.append(SequenceCriteriaNodeModel() # a node with no criteria specified sequence_query.relationship_sequence.append(SequenceCriteriaRelationshipModel()) #a realtoinship with no criteria sequence_query.node_sequence.append(SequenceCriteriaNodeModel(component_type="widget", include_with_return=True)) + The sequence query must always have 1 more node than relationship. + The order is important, and is a sequence. node - relationship - node - relationship - nodepython result = await match_util.sequence_query(sequence_query=sequence_query) ``` Run a specific query, lets delete everything python await database_operations.run_query(query=f"match (n) detach delete n") Not Implemented Update a node Update a sequence Delete a node
Latest version: 0.3.7 Released: 2023-08-17
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