Saravanan666/pypi-org huggingface dataset:
Package: pydantic-consul-settings
Pydantic Consul settingsAdd Consul as source of env variable to settingsThis package provides a way to usepydanticsettings withconsulas source of environment variables.Installationpipinstallpydantic-consul-settingsUsagefrompydantic_consul_settingsimportBaseSettingsWithConsul,ConsulClientSettings,SettingsConfigDictclassConsulSettings(ConsulClientSettings):"""Add additional settings for key generation"""stage:str='dev'service:str='my-service'@propertydefkey_prefix(self)->str:"""Get the key prefix."""returnf"{self.stage}/{self.service}"classBaseSettings(BaseSettingsWithConsul):model_config=SettingsConfigDict(env_prefix='APP_',consul_model=ConsulSettings(),)classSettings(BaseSettings):"""App settings"""model_config=SettingsConfigDict(env_prefix='APP_',)# Get from env APP_NAME# and `dev/my-service/APP_NAME` from consulname:str='my-app'# Get from env APP_VERSION# and `dev/my-service/APP_VERSION` from consulversion:str='0.1.0'# Get from env APP_DESCRIPTION# and `dev/my-service/APP_DESCRIPTION` from consuldescription:str='My app description'settings=Settings()print(settings.dict())
Package: pydantic-custom-types
pydantic custom typesA collection of custom types for pydantichttps://github.com/pydantic/pydanticUseful for validation input parameters for infrastructure pipelines when building kubernetes apps/clustersRequirementspython >= 3.10Installationpip install pydantic-custom-typesExamplesfrompydanticimportBaseModelfrompydantic_custom_types.kubernetesimportNamespaceName,SecretNameclassK8sNamespace(BaseModel):# These string types only allow: lowercase/numbers/dash, cannot start with dash/number# NamepaceName has linit at 63 characters# SecretName has linit at 63 charactersname:NamespaceNamesecret_name:SecretName# will passK8sNamespace(name="my-namespace",secret_name="my-secret")# will not passK8sNamespace(name="-0mynameSpace",secret_name="0mysecret")
Package: pydantic-databricks
Pydantic DatabricksOverviewThis library leverages Pydantic to simplify the generation of Databricks SQL queries for managing tables.
It provides a convenient way to define table schemas using Pydantic models and generates corresponding SQL statements.Installationpipinstallpydantic-databricksUsage1. Basic Example Table Creationfrompydantic_databricksimportDatabricksModelfrompyspark.sqlimportSparkSessionspark=SparkSession.builder.getOrCreate()classSchema(DatabricksModel):_table_name="test"_schema_name="test_schema"col1:strcol2:intcol3:floatspark.sql(Schema.create_table())Generated SQL:CREATETABLEtest_schema.test(col1STRINGNOTNULL,col2BIGINTNOTNULL,col3DOUBLENOTNULL)USINGDELTA;2. Setting Grantsfrompydantic_databricksimportDatabricksModel,Grant,GrantActionfrompyspark.sqlimportSparkSessionspark=SparkSession.builder.getOrCreate()classSchema(DatabricksModel):_table_name="test"_schema_name="default"_grants={Grant(action=GrantAction.MODIFY,principal="user1"),Grant(action=GrantAction.SELECT,principal="user2"),}col1:strforgrantinSchema.grant_statements():spark.sql(grant)Currently Supported Options_catalog_name: The catalog name for the table. Default isNone. IfNonethen a two part namespace is used._schema_name: The schema name for the table (required)._table_name: The name of the table (required)._grants: A set of Grant objects. Default isNone._location_prefix: The location prefix for external tables. Default isNone. If set, then the table is created as an external table. The prefix will be appended with the full table name._table_properties: A dictionary of table properties._table_create_mode: The mode for table creation. Default isCreateMode.CREATE._table_data_source: The data source for the table. Default isDataSource.DELTA._partition_columns: A list of partition columns for the table. Default isNone._options: A dictionary of additional options for table creation. Default isNone._comment: A comment for the table. Default isNone.Coming soonSupport for table and column constraintsContributingWe welcome contributions to pydantic-databricks! If you'd like to contribute, please follow these steps:Fork the repository.Create a branch for your feature or bug fix.Make your changes.Test your changes thoroughly.Submit a pull request.Licensepydantic-databricks is licensed under the MIT License. SeeLICENSEfor more information
Package: pydantic-db-backend
TestingCouchDBhttp://localhost:5984/_utils/#user: adminpasswd: pytestInitializationAutomatic initialization from environmentinit_backend()Manual initializationExample for MongoDB with alias.If missing, the default for alias is"default"MongoDbBackend(alias="people")client=Backend.client(alias="people")PaginationUsage with routers@router.get("/people")@pagination()defpeople_get():returnBackend.client().get_instances(PeopleModel)Custom usage in codepagination_params=PaginationParameterModelwithpagination_provider(pagination_params)asp:Backend.client().get_instances(PeopleModel)pagination_params=PaginationParameterModelwithpagination_provider(pagination_params)asp:Backend.client().get_instances(PeopleModel)pagination_params=PaginationParameterModelwithpagination_parameter_provider(pagination_params):objs,max_results=Backend.client().pagination_aggregate(agg)returnpagination_result((objs,max_results))
Package: pydantic-dbmodel-core
Pydantic DbModel CoreOverviewThepydantic-dbmodel-corelibrary presents theDbModelCoreclass, an augmentation of theBaseModelclass from Pydantic. This enhancement is achieved through a change in theModelMetaclassmeta-class, enabling the coexistence of class variables and instance variables with identical names. This feature, available in Pydantic V1 but absent in Pydantic V2, has been reintroduced with this small yet crucial modification.InstallationTo installpydantic-dbmodel-core, run the following command:pipinstallpydantic-dbmodel-coreUsageImport theDbModelCoreclass from the library and use it as you would use Pydantic'sBaseModel.frompydantic_dbmodel_coreimportDbModelCoreclassYourModel(DbModelCore):# Define your fields herepassFeaturesAllows the definition of class variables with the same name as instance variables.Fully compatible with Pydantic's field definitions and validators.
Package: pydantic-decoder
Convert json text back into proper Pydantic models.Simple Examplefrompydantic_decoderimportDecoderModel,encode,decodeclassMyModel(DecoderModel):first_name:strlast_name:strmodel=MyModel(first_name='John',last_name='Doe')msg=model.json()m=model.decode(msg)assertm==modelassertisinstance(m,MyModel)Registration ExamplesUse your current models by only changing the inheritance frompydantic.BaseModeltopydantic_decoder.DecoderModel.frompydantic_decoderimportDecoderModel,register_model,encode,decodeclassMyModel(DecoderModel):first_name:strlast_name:strclassMyModel2(DecoderModel):first_name:strlast_name:str# Subclasses of the DecoderModel are registered automatically# register_model(MyModel)# register_model('Model2', MyModel2)model=MyModel(first_name='John',last_name='Doe')msg=encode(model)m=decode(msg)assertm==modelassertisinstance(m,MyModel)model2=MyModel2(first_name='John',last_name='Doe')msg=encode(model2)m2=decode(msg)assertm2==model2assertisinstance(m2,MyModel2)
Package: pydantic-dict
pydantic_dictApydanticmodel subclass that implements Python's dictionary interface.Example:frompydantic_dictimportBaseModelDictclassUser(BaseModelDict):id:intname:str="Jane Doe"user=User(id=42)user["session_id"]="95607c42-250a-4913-9dfb-00eb6535e685"assertuser.session_id=="95607c42-250a-4913-9dfb-00eb6535e685"assertuser["session_id"]=="95607c42-250a-4913-9dfb-00eb6535e685"user.pop("session_id")assert"session_id"notinuserassertuser.get("last_name",None)isNoneuser.update({"email":"jane.doe@email.com"})print(user.json())# >>> {"id": 42, "name": "Jane Doe", "email": "jane.doe@email.com"}user.clear()# fields are NOT removed. only non-fields are removedprint(user.json())# >>> {"id": 42, "name": "Jane Doe"}user.setdefault("last_active","2023-01-01T19:56:10Z")deluser["last_active"]Unsetmarker typeTheUnsetmarker type provides a way to "mark" that an optional model field
is by default not set and is not required to construct the model. This enables
more semantic usage of built-in dict methods likeget()andsetdefault()that can return or set a default value. Likewise, fields that areUnsetare
not considered to be members of aBaseModelDictdictionary (e.g."unset_field" not in model_dict) and are not included in__iter__(),keys(),values(), orlen(model_dict). This feature is especially useful
when refactoring existing code to use pydantic.Example:frompydantic_dictimportBaseModelDict,UnsetfromtypingimportOptionalclassUser(BaseModelDict):id:intname:str="Jane Doe"email:Optional[str]=Unsetuser=User(id=42)assert"email"notinuseruser["email"]# raises KeyErrorassertlen(user)==2assertset(user.keys())=={"id","name"}user.setdefault("email",f"{user.id}@service.com")# returns `42@service.com`assert"email"inuserInstallpipinstallpydantic_dict
Package: pydantic-dict-encoders
Pydantic Dict EncodersSimple wrapper of pydantic for support custom dict encoders like json encodersThis wrapper created for solve serialization problem in ariadne resolvers, where needed return dict only with simple objects.
After researchsome problemsand pydantic features, it was decided to make this wrapper more like a crutch for solve my problem.This should be resolved inPydantic V2, but it's not production ready yet.
And even there is aPRthat was made some time ago. But for now, it seemed to me sufficient to use this solution and perhaps it will be useful to someone else.Thanks to @samuelcolvin for create and being active on pydantic and starting to solve problems before some people think about them! :)IMPORTANT!Remember: this is a crutch that you use at your own risk. It will most likely not be needed after some time, but if everything suits you - go for it ;)UsageThis wrapper has 2 possibilities:Define custom dict encoders that work the same as pydanticjson_encoderswhen callingmodel.dict()Encode each field value as if they were passed to pydantic json.To use this just inherit your model fromPydanticDictEncodersMixin:classAnyModel(PydanticDictEncodersMixin,BaseModel):any_field:str|None=NoneclassConfig:dict_encoders={}jsonify_dict_encode=FalseWARNING!Please, remember about python MRO: BaseModel MUST BE after mixin.Pros and consPros:Pretty simple and fast way to get the required behavior when exporting to a python dictCons:In nested models that do not inherit from the mixin, serialization will breakDirty decision
Package: pydantic-duality
Automatically and lazily generate three versions of your pydantic models: one with Extra.forbid, one with Extra.ignore, and one with all fields optionalInstallationpipinstallpydantic-dualityQuickstartGiven the following models:frompydantic_dualityimportDualBaseModelclassUser(DualBaseModel):id:UUIDname:strclassAuth(DualBaseModel):some_field:struser:UserUsing pydantic-duality is roughly equivalent to making all of the following models by hand:frompydanticimportBaseModel# Equivalent to User and User.__request__classUserRequest(BaseModel,extra=Extra.forbid):id:UUIDname:str# Rougly equivalent to Auth and Auth.__request__classAuthRequest(BaseModel,extra=Extra.forbid):some_field:struser:UserRequest# Rougly equivalent to User.__response__classUserResponse(BaseModel,extra=Extra.ignore):id:UUIDname:str# Rougly equivalent to Auth.__response__classAuthResponse(BaseModel,extra=Extra.ignore):some_field:struser:UserResponse# Rougly equivalent to User.__patch_request__classUserPatchRequest(BaseModel,extra=Extra.forbid):id:UUID|Nonename:str|None# Rougly equivalent to Auth.__patch_request__classAuthPatchRequest(BaseModel,extra=Extra.forbid):some_field:str|Noneuser:UserPatchRequest|NoneSo it takes you up to 3 times less code to write the same thing. Note also that pydantic-duality does everything lazily so you will not notice any significant performance or memory usage difference when using it instead of writing everything by hand. Think of it as using all the customized models as cached properties.Inheritance, inner models, custom configs,custom names, config kwargs, isinstance and subclass checks work intuitively and in the same manner as they would work if you were not using pydantic-duality.HelpSeedocumentationfor more details
Package: pydantic-env-settings
Pydantic Env SettingsWrapper aroundBaseSettings.Sets the usage of the .env file as default.Modifies the error description while parsing .env file:marks it is a settings validation errorrenames the field names by adding the env_prefix and uppercaseing itgives hint about .env fileInstallationUsing pip:pip install pydantic-env-settingsUsageclassMySettings(EnvSettings):filename:strverbose:boolclassConfig:env_prefix='MY_'settings=MySettings()print(settings.filename)print(settings.verbose)Then your .env file should contain:MY_FILENAME=/tmp/tempfile.binMY_VERBOSE=trueIf your .env file does not exists or you have type errors in it you will see an error message like:SettingsError: 2 validation errors for MySettings
MY_FILENAME
  field required (type=value_error.missing)
MY_VERBOSE
  field required (type=value_error.missing)

Hint! Verify your environment setting or the '.env' file.
Package: pydantic-errors-messages-translations
Pydantic Errors Messages TranslationsIt's a collection of translations for pydantic errors in any languages;InstallationUse the package managerpipto install foobar.pipinstallpydantic-errors-messages-translationspydantic-i18nUsagefrompydantic_errors_messages_translationsimporttranslations,convert_error_to_human_readableYOUR_LANGUAGE='pt_BR'error_translation=PydanticI18n(translations,default_locale=YOUR_LANGUAGE)classUser(BaseModel):name:str=Field(min_length=40)email:str=Field(min_length=24)city:strtry:wrong_user=User(name='Irineu Evangelista de Sousa',city='Maua')exceptValidationErrorase:errors_as_dict=error_translation.translate(e.errors(),YOUR_LANGUAGE)raiseException(convert_error_to_human_readable(errors_as_dict))ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
Package: pydantic-external-settings-v1
pydantic-external-settings-v1This module provides a way to load settings from any external source, when using pydantic BaseSettings.Quickstartfrompydantic_external_settingsimportExternalSourceConfigfrompydanticimportBaseSettingsfromtypingimportClassVarclassApolloSourceConfig(ExternalSourceConfig):def__init__(self,validation_alias:str=None,*,default_value=None):super().__init__(self.get_from_apollo,validation_alias,default_value=default_value)defget_from_apollo(self,key):returnkey+"_***"classS3Settings(BaseSettings):api_key:str="api_key"bucket:ClassVar[str]=ApolloSourceConfig()classConfig:env_file='.env's3_settings=S3Settings()print(s3_settings.bucket)ExternalSourceConfigUsageExternalSourceConfigis a class descriptor, which can be used to load settings from any external source.
Note that the typing annotation is required to beClassVarfor theExternalSourceConfigattribute, so that it will
not be considered as a field of the settings class. Currently, theExternalSourceConfigsupports to speacify avalidation_aliasto override the name of setting field, and adefault_valueto provide a default value when the
settings field is not found both in the external source and the inner source(like .env file and environment variables).To use a specific external usage, like database, you can create a subclass ofExternalSourceConfigand provide a callable to the__init__method, which will be called to get the value of the settings field. Note that
if
the field setting is not found in the external source, the callable should return None, so that the default value can be
used.
Package: pydantic-factories
⚠️The next version of this library is released aspolyfactory. Users are encouraged to migrate to it.⚠️Pydantic-FactoriesThis library offers powerful mock data generation capabilities forpydanticbased models,dataclassesandTypeDicts. It can also be used with other libraries that use pydantic as a foundation.Check outthe documentation 📚.Installationpipinstallpydantic-factoriesExamplefromdatetimeimportdate,datetimefromtypingimportList,UnionfrompydanticimportBaseModel,UUID4frompydantic_factoriesimportModelFactoryclassPerson(BaseModel):id:UUID4name:strhobbies:List[str]age:Union[float,int]birthday:Union[datetime,date]classPersonFactory(ModelFactory):__model__=Personresult=PersonFactory.build()That's it - with almost no work, we are able to create a mock data object fitting thePersonclass model definition.This is possible because of the typing information available on the pydantic model and model-fields, which are used as a
source of truth for data generation.The factory parses the information stored in the pydantic model and generates a dictionary of kwargs that are passed to
thePersonclass' init method.Features✅ supports both built-in and pydantic types✅ supports pydantic field constraints✅ supports complex field types✅ supports custom model fields✅ supports dataclasses✅ supports TypedDictsWhy This Library?💯 powerful💯 extensible💯 simple💯 rigorously testedContributingThis library is open to contributions - in fact we welcome it.Please see the contribution guide!
Package: pydantic-factur-x
pydantic-factur-xThe main feature of this Python library is to generate Factur-X and Order-X xml files.
It uses pydantic to make more easy, accessible and idiomatic the manipulation of all the elements defined in Factur-X and order-X.
No need to hassle with xml, only use pydantic object models.What is factur-X ?Factur-X is a Franco-German standard for hybrid e-invoice (PDF for users and XML data for process automation), the first implementation of the European Semantic Standard EN 16931 published by the European Commission on October 16th 2017. Factur-X is the same standard than ZUGFeRD 2.2.Factur-X is at the same time a full readable invoice in a PDF A/3 format, containing all information useful for its treatment, especially in case of discrepancy or absence of automatic matching with orders and / or receptions, and a set of invoice data presented in an XML structured file conformant to EN16931 (syntax CII D16B), complete or not, allowing invoice process automation.The first objective of Factur-X is to enable suppliers, invoice issuers, to create added-value e-invoices, containing a maximum of information in structured form, according to their ability to produce them in this form, and to let customers recipients free to use the invoice data and / or the readable presentation, depending on their needs and their invoice process maturity on automation.order-xOrder-X is the implementation of Factur-X for purchase orders.Installation(tbd)Usage(tbd)LicenseThis library is published under the MIT licence
Package: pydantic-fetch
Pydantic-fetchExtension ofpydantic.BaseModelwhich supports sending and parsing from HTTP endpoints.DescriptionBaseModelis extended with two class functions:fetchto recieve a json payload from an endpoint and validate it as the pydantic modelsubmitto send a pydantic model to an endpoint as a json payload.Usagefrompydantic_fetchimportBaseModelclassUser(BaseModel):id:strname:strdefsend_user(endpoint,id:str,name:str):user=User(id=id,name=name)user.submit(endpoint)defget_user(endpoint):user=User.fetch(endpoint)
Package: pydantic-fhir
This stub for FHIR generated byfhirzeug.FormatAll profiles are in one file.FHIR Specific JSON RepresentationGenerally this generated code tries to stick as close as possible to theFHIR JSON spec. Another important is theFHIR Datatypes spec.Empty StringsString property values can never be empty. Either the property is absent, or it is present with at
least one character of content. -https://www.hl7.org/fhir/STU3/json.htmlAdditionally whitespaces are stripped:Note: This means that a string that consists only of whitespace could be trimmed to nothing, which
would be treated as an invalid element value. Therefore strings SHOULD always contain
non-whitespace content. -https://www.hl7.org/fhir/datatypes.html#primitiveThat means empty strings are interpreted asnullvalues.
This could lead to invalid arrays([""]). This follows the behavior fromHAPIandVonk.DateTime ValuesDatetime values are strings as well. That means an empty string or a string with whitespaces is
threaded as anullvalue. Which then is not set at all.nullValuesJust as in XML, JSON objects and arrays are never empty, and properties never have null values
(except for a special case documented below). Omit a property if it is empty -https://www.hl7.org/fhir/json.html#xmlThat means specifically that if a property contains a null value it is like it never has been set.Example:>>>fromr4importPatient>>>Patient(name=None).dict(){}ValueSets and CodeSystemsFHIR Specification provides different ways to define aValueSet. The implementation varies depending on the use case :If a ValueSet is based on a single CodeSystem and this CodeSystem is defined in FHIR, then the ValueSet is validated by anenum.If a ValueSet is based on a single CodeSystem, that this CodeSystem is not included in the FHIR specification, but FHIR provides an exhaustive list of possible values, then the ValueSet is validated by atyping.Literal.Otherwise, the field is validated by a very permissive regex[^\s]+(\s[^\s]+)*.
Package: pydantic-forms
Pydantic formsA Python package that lets you add smart forms toFastAPIandFlask. 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
usingPydanticmodels.Documentation regarding the usage of Forms can be foundhereInstallation (Development standalone)Install the project and its dependencies to develop on the code.Step 1 - install flit:python3-mvenvvenvsourcevenv/bin/activate
pipinstallflitStep 2 - install the development code:flitinstall--depsdevelop--symlink--pythonvenv/bin/python!!! danger
Make sure to use the flit binary that is installed in your environment. You can check the correct
path by runningshell which flitTo be sure that the packages will be installed against the correct venv you can also prepend the python interpreter
that you want to use:flitinstall--depsdevelop--symlink--pythonvenv/bin/pythonRunning testsRun the unit-test suite to verify a correct setup.Step 2 - Run testspytesttests/unit_testsor with xdist:pytest-nautotests/unit_testsIf 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 thepydantic-formsand you want to test your new form features
against it, you can use someflitmagic 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:python-mvenvvenvsourcevenv/bin/activate
pipinstallflitStep 2 - symlink the core to your own projectflitinstall--depsdevelop--symlink--python/path/to/a/project/venv/bin/pythonIncreasing 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:bumpversionpatch--new-version0.0.1Note: specifying it like this, instead of relying on bumpversion itself to increase the version, allows you to
set a "RC1" version if needed.