Saravanan666/pypi-org huggingface dataset:
Package: pydantic-gen
What this package doesThis is a code generation package that converts YML definitions to Pydantic models (either python code or python objects).What is PydanticPydanticis a python library for data validation and settings management using
python type annotations.Take a look at theofficial examplefrom the Pydantic docs.Why generate schemas?Normally you just program the schemas within your program, but there are several
use cases when code generation makes a lot of sense:You’re programming several apps that use the same schema (think an API server and client library for it)You’re programming in more than one programming languageGetting startedInstallationUsing pip:pipinstallpydantic-genUsingpoetry:poetryaddpydantic-genUsageFirst you need to create a YAML file with your desired class schema. Seeexample.ymlfile.frompydantic_genimportSchemaGengenerated=SchemaGen('example.yml')The code is now generated and stored ingenerated.codeattribute. There are
two ways to use the code:Save it to a file, and use the file in your program:generated.to_file('example_output.py')You can inspect the resulting file in theexample_output.pyOr directly import the generated classed directly without saving:generated.to_sys(module_name='generated_schemas')After runninggenerated.to_sys(module_name=’generated_schemas’your generated code will be available for import:importgenerated_schemasasgsschema=gs.GeneratedSchema1(id=1)Usage patternRecommended usage pattern is creating the yaml files needed for your projects
and storing them in a separate repository, to achieve maximum consistency across all projects.YAML-file structureschemas- list of all schemas describedname- name of the generated classprops- list of properties of the class using python type
annotation. Fields:name- field name,type- field type,optional- bool, if True the type will be wrapped inOptional,default- default value for the field.config- list of config settings fromModel Configof pydantic.TestingProject is fully covered by tests and uses pytest. To run:pytestPackaging NoticeThis project uses the excellentpoetryfor packaging. Please read about it and let’s all start usingpyproject.tomlfiles as a standard. Read more:PEP 518 – Specifying Minimum Build System Requirements for Python ProjectsWhat the heck is pyproject.toml?Clarifying PEP 518 (a.k.a. pyproject.toml)
Package: pydantic-generator
pydantic-generatorpydantic-generator generates a pydantic schema module from a json file.installpydantic-generates usesast.unparse()and therefore only supports python 3.9+.$python3.9-mpipinstallpydantic-generator
$pydanticgen--help
usage:pydanticgen[-h]-iINPUT_[-oOUTPUT]optionalarguments:-h,--helpshowthishelpmessageandexit-iINPUT_,--input_INPUT_,--inputINPUT_-oOUTPUT,--outputOUTPUTexample$ls
response.json
$catresponse.json{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}# this command generates Response.json$pydanticgen-iresponse.json
$ls
response.jsonResponse.py
$catResponse.py
frompydanticimportBaseModel

classResponse(BaseModel):classMenu(BaseModel):id:strvalue:strclassPopup(BaseModel):classMenuitem(BaseModel):value:stronclick:strmenuitem:list[Menuitem]popup:Popupmenu:Menu(This sample can be found athttps://json.org/example.html.)
Package: pydantic-handler-converter
Pydantic-handler-converterThis code simplifies the conversion of Pydantic schemas into Aiogram handler groups,
making it easy to create form-filling handlers.Installationpipinstallpydantic_handler_converterUsage:>>>fromenumimportEnum>>>fromtypingimportUnion>>>frompydanticimportBaseModel>>>frompydantic_handler_converterimportBasePydanticFormHandlers# ----------------------------------------Simple datatypes schema-------------------------------------->>>classPersonPydanticFormSchema(BaseModel):...name:str...age:int...height:float...>>>classPersonFormHanlders(BasePydanticFormHandlers[PersonPydanticFormSchema]):...pass......>>>dirs=dir(PersonFormHanlders)>>>assertlen(tuple(filter(lambdax:notxindirs,['name_view','age_view','height_view'])))==0>>>assertPersonFormHanlders(finish_call=None)# ----------------------------------------Enum datatype schema----------------------------------------->>>classMood(Enum):...HAPPY="😄 Happy"...SAD="😢 Sad"...EXCITED="🤩 Excited"...RELAXED="😌 Relaxed"...>>>>>>>>>classPersonMoodPydanticFormSchema(BaseModel):...name:str...current_mood:Mood...>>>classPersonMoodFormHanlders(BasePydanticFormHandlers[PersonMoodPydanticFormSchema]):...pass......>>>dirs=dir(PersonMoodFormHanlders)>>>assertlen(tuple(filter(lambdax:notxindirs,['name_view','current_mood_view'])))==0>>>assertPersonMoodFormHanlders(finish_call=None)# ----------------------------------------Complex schema----------------------------------------------->>>classAddress(BaseModel):...street:str...city:str...postal_code:str...>>>classPerson(BaseModel):...name:str...age:int...address:Address......>>>classPersonFormHanlders(BasePydanticFormHandlers[Person]):...pass......>>>dirs=dir(PersonFormHanlders)>>>assertlen(tuple(filter(lambdax:notxindirs,...['name_view','address_street_view','address_city_view','address_postal_code_view']...)))==0...>>>assertPersonFormHanlders(finish_call=None)# ------------------------------------Combined Enum datatype schema------------------------------------>>>classHappyMood(Enum):...HAPPY="😄 Happy"...>>>classSadMood(Enum):...SAD="😢 Sad"...>>>classExcitedMood(Enum):...EXCITED="🤩 Excited"...>>>classRelaxedMood(Enum):...RELAXED="😌 Relaxed"...>>>>>>classPersonMoodPydanticFormSchema(BaseModel):...name:str...current_mood:Union[HappyMood,SadMood,ExcitedMood,RelaxedMood]...future_mood:HappyMood|SadMood|ExcitedMood|RelaxedMood......>>>classPersonMoodFormHanlders(BasePydanticFormHandlers[PersonMoodPydanticFormSchema]):...pass......>>>dirs=dir(PersonMoodFormHanlders)>>>assertlen(tuple(filter(lambdax:notxindirs,['name_view','current_mood_view'])))==0>>>assertPersonMoodFormHanlders(finish_call=None)
Package: pydantic-jsonapi
pydantic-jsonapian implementation of JSON:api using pydantic for validationfrompydantic_jsonapiimportJsonApiModelfrompydanticimportBaseModelclassItem(BaseModel):name:strquantity:intprice:floatItemRequest,ItemResponse=JsonApiModel('item',Item)# request validationrequest={'data':{'type':'item','attributes':{'name':'apple','quantity':10,'price':1.20,},}}ItemRequest(**request)#response validationresponse={'data':{'id':'abc123','type':'item','attributes':{'name':'apple','quantity':10,'price':1.20,},'relationships':{'store':{'links':{'related':'/stores/123'}}}},'links':{'self':'/item/abc123'}}ItemResponse(**response)
Package: pydantic-kedro
pydantic-kedroAdvanced serialization forPydanticmodels
viaKedroandfsspec.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 thedocumentationfor a tutorial
and more examples.Usage with KedroYou can use the [PydanticAutoDataSet][pydantic_kedro.PydanticAutoDataSet]
or any other dataset frompydantic-kedrowithin yourKedro catalogto save your Pydantic models:# conf/base/catalog.ymlmy_pydantic_model:type:pydantic_kedro.PydanticAutoDataSetfilepath:folder/my_modelDirect Dataset UsageThis example works for "pure", JSON-safe Pydantic models viaPydanticJsonDataSet:frompydanticimportBaseModelfrompydantic_kedroimportPydanticJsonDataSetclassMyPureModel(BaseModel):"""Your custom Pydantic model with JSON-safe fields."""x:inty:strobj=MyPureModel(x=1,y="why?")# Create an in-memory (temporary) file via `fsspec` and save itds=PydanticJsonDataSet("memory://temporary-file.json")ds.save(obj)# We can re-load it from the same fileread_obj=ds.load()assertread_obj.x==1Standalone UsageYou can also usepydantic-kedroas a generic saving and loading engine for
Pydantic models:fromtempfileimportTemporaryDirectoryfrompydanticimportBaseModelfrompydantic_kedroimportload_model,save_modelclassMyModel(BaseModel):"""My custom model."""name:str# We can use any fsspec URL, so we'll make a temporary folderwithTemporaryDirectory()astmpdir:save_model(MyModel(name="foo"),f"{tmpdir}/my_model")obj=load_model(f"{tmpdir}/my_model")assertobj.name=="foo"
Package: pydantic-kms-secrets
pydantic-kms-secretsUtility to decrypt and encrypt secrets usingAWS KMS keysthat also integrates withpydanticmodels which allows for
encrypted values to be stored in.envfiles and be decrypted at runtime.InstallationFrom PyPi:$pipinstallpydantic-kms-secretsUsageCLIEncrypt a secret:$pks-kyour-kms-key-id-vmy-secret-password-eDecrypt a secret:$pks-kyour-kms-key-id-vyour-encrypted-secret-dHelp docs:$pks--help
usage:pks[-h][-kKEY_ID]-vVALUE[-e][-d]TooltoencryptanddecryptsecretsviaaKMSkey

optionalarguments:-h,--helpshowthishelpmessageandexit-kKEY_ID,--key-idKEY_IDIDoftheKMSkeytouse-vVALUE,--valueVALUEThevaluetobeencrypted-e,--encryptSettoencryptvalue-d,--decryptSettodecryptvaluePydanticPydantic KMS Secrets is able to integrate and add functionality on top of Pydantic'sdotenv extensionby allowing you
to store encrypted values in your.envfiles and decrypt them at runtime. A basic implementation
would look something like:Pydantic Settings ModelfrompydanticimportBaseSettingsfrompydantic_kms_secretsimportKMSSecretStr,decrypt_kms_secretsclassSettings(BaseSettings):env:strsecrets_kms_key_id:str# This model attribute must exist to decrypt secretskms_secret_1:KMSSecretStrkms_secret_2:KMSSecretStrclassConfig:env_file=".env"# Don't forget to call decrypt_kms_secrets, if you don't the secrets will not be decryptedsettings=decrypt_kms_secrets(Settings()).envFileENV="prod"SECRETS_KMS_KEY_ID="your-kms-key-id"# This environment variable must be set to decrypt secretsKMS_SECRET_1="my-first-encrypted-secret"KMS_SECRET_2="my-second-encrypted-secret"KMSSecretStrClassTheKMSSecretStrclass is almost identical to theSecretStrtype in pydantic.# This example uses the settings value from the python example above# Standard access methods will not display the secretprint(settings)#> env='prod' secrets_kms_key_id='your-kms-key-id' kms_secret_1=KMSSecretStr('**********') kms_secret_2=KMSSecretStr('**********')print(settings.kms_secret_1)#> **********print(settings.dict())"""{'env': 'prod','secret_kms_key_id': 'your-kms-key-id','kms_secret_1': KMSSecretStr('**********'),'kms_secret_2': KMSSecretStr('**********'),}"""print(settings.json())#> {"env": "prod", "secret_kms_key_id": "your-kms-key-id", "kms_secret_1": "**********", "kms_secret_2": "**********"}# Use get_secret_value method to see the secret's content.print(settings.kms_secret_1.get_secret_value())#> my-first-encrypted-secretprint(settings.kms_secret_2.get_secret_value())#> my-second-encrypted-secret
Package: pydantic_lambda_handler
VisionAim to create an easy-to-use decorator on a lambda for quick development of apis on AWS lambda using AWS Gateway.Inspired by, and attempting to match theFast APIapi.Currently, I'm working through the first steps to hit the basics.This is very much at the beginning of the project, so I could do with all the help I can get :DMUST HAVEcreates open api schemaAPI Gateway Lambda proxy integrationhttps://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-formathttps://docs.aws.amazon.com/lambda/latest/dg/services-apigateway-tutorial.htmlpip install --target ./demo_app ../.
Package: pydantic_loader
PyConfigConfiguration management using pydantic and a bit of sugar.This library provides a load and save functions to load and save serialized pydantic settings.
Settings can be saved in.json,.yamland.tomlformat.Installationpip install pydantic_loaderfor loading and saving json files.pip install pydantic_loader[yaml]for loading and saving yaml and json files.pip install pydantic_loader[toml]for loading and saving toml and json."""Simple example."""frompathlibimportPathfrompydantic_loaderimportload_json,save_jsonfrompydanticimportBaseSettingsclassDummyConfig(BaseSettings):"""An app configuration class"""a:int=1b:str="ABC"config=DummyConfig()save_json(config,Path("config.json"))config=load_json(DummyConfig,Path("config.json"))
Package: pydantic-loggings
Configure 🎁 Your 🤗 Python 🐍 Logging 📝Installationpipinstallpydantic-loggingsUsageexamplesout of the boxfrompydantic_loggings.baseimportLogginglogger=Logging().get_logger(configure=True)logger.debug('debug')logger.info('info')logger.warning('warning')# 01-01 00:00:00 DEBUG   debug# 01-01 00:00:00 INFO    info# 01-01 00:00:00 WARNING warningDefault Loggingfrompydantic_loggings.not_setimportLogginglogger=Logging().get_logger(configure=True)logger.debug('debug')logger.info('info')logger.warning('warning')# warningConfigure from EnvironmentfrompathlibimportPathfrompydantic_loggings.not_setimportLoggingenv_file=Path(__file__).parent/'.env'logger=Logging(_env_file=env_file).get_logger(configure=True)logger.debug('debug')logger.info('info')logger.warning('warning')# 01-01 00:00:00 [root]   DEBUG (main.py:11) debug# 01-01 00:00:00 [root]    INFO (main.py:12) info# 01-01 00:00:00 [root] WARNING (main.py:13) warning# .envlog__formatters__my_formatter__datefmt='%m-%d %H:%M:%S'log__formatters__my_formatter__format='{asctime} [{name}] {levelname:>7} ({filename}:{lineno}) {message}'log__formatters__my_formatter__style='{'log__handlers__my_handler__class_='logging.StreamHandler'log__handlers__my_handler__formatter='my_formatter'log__loggers__root__level='DEBUG'log__loggers__root__handlers='["my_handler"]'# is equivalent to:# log__formatters__my_formatter='{"datefmt":"%m-%d %H:%M:%S","format":"{asctime} [{name}] {levelname:>7} ({filename}:{lineno}) {message}","style":"{"}'# log__handlers__my_handler='{"class_":"logging.StreamHandler","formatter":"my_formatter"}'# log__loggers__root='{"level":"DEBUG","handlers":["my_handler"]}'# and/or:# log__formatters='{"my_formatter":{"datefmt":"%m-%d %H:%M:%S","format":"{asctime} [{name}] {levelname:>7} ({filename}:{lineno}) {message}","style":"{"}}'# log__handlers='{"my_handler":{"class_":"logging.StreamHandler","formatter":"my_formatter"}}'# log__loggers='{"root":{"level":"DEBUG","handlers":["my_handler"]}}'Loggingsnot_setbaserich
Package: pydantic-marshals
Pydantic MarshalsLibrary for creating partial pydantic models (automatic converters) from different mappings. Currently, it consists of basic boilerplate parts and functional implementation for sqlalchemy 2.0+ (included via extra)Base InterfaceTBAImplementationsTBASQLAlchemy: Basic usage# sqlalchemy 2.0+ is requiredfromsqlalchemyimportForeignKey,String,Textfromsqlalchemy.ormimportMapped,mapped_column,relationshipfrompydantic_marshals.sqlalchemyimportMappedModelclassAvatar(Base):__tablename__="avatars"id:Mapped[int]=mapped_column(primary_key=True)IdModel=MappedModel.create(columns=[id])classUser(Base):__tablename__="users"id:Mapped[int]=mapped_column(primary_key=True)name:Mapped[str]=mapped_column(String(100))description:Mapped[str|None]=mapped_column(Text())admin:Mapped[bool]=mapped_column()# empty `mapped_column()` is required for modelsavatar_id:Mapped[int]=mapped_column(ForeignKey("avatars.id"))avatar:Mapped[Avatar]=relationship()@propertydefrepresentation(self)->str:returnf"User #{self.id}:{self.name}"BaseModel=MappedModel.create(columns=[id])CreateModel=MappedModel.create(columns=[name,description])PatchModel=CreateModel.as_patch()IndexModel=MappedModel.create(properties=[representation])FullModel=BaseModel.extend(columns=[admin],relationships=[(avatar,Avatar.IdModel)],includes=[CreateModel,IndexModel],)withsessionmaker.begin()assession:user=User(name="alex",description="cool person",avatar=Avatar(),admin=False)session.add(user)session.flush()print(User.BaseModel.model_validate(user).model_dump())# {"id": 0}print(User.PatchModel.model_validate({}).model_dump(exclude_defaults=True))# {}print(User.PatchModel.model_validate({"description":None}).model_dump(exclude_defaults=True))# {"description": None}print(User.CreateModel.model_validate(user).model_dump())# {"name": "alex", "description": "cool person"}print(User.IndexModel.model_validate(user).model_dump())# {"representation": "User #0: alex"}print(User.FullModel.model_validate(user).model_dump())# {#   "id": 0,#   "name": "alex",#   "description": "cool person",#   "representation": "User #0: alex",#   "avatar": {"id": 0},#   "admin": False# }Assert ContainsThe "assert contains" is an interface for validating data, mainly used in testing. Use"assert-contains"extra to install this module:pipinstallpydantic-marshals[assert-contains]Documentation:Usage with ExamplesLocal developmentClone the repositorySetup python (the library is made with python 3.10+)Install poetry (should work with v1.4.1)Install dependenciesInstall pre-commit hooksCommands to use:pipinstallpoetry==1.4.1
poetryinstall
pre-commitinstall
Package: pydantic-mermaid
Pydantic MermaidTo convert Pydantic models to Mermaid charts, you can use thepydantic-mermaidlibrary. This library allows you to generate Mermaid charts from your Pydantic models. Here are the steps to install and use pydantic-mermaid:If you are using pydantic 2, please visithttps://github.com/EricWebsmith/pydantic-2-mermaidUse in terminalInstall thepydantic-mermaidlibrary using pip:pipinstallpydantic-mermaidUse command linepydantic-mermaid--modulemodels.py--outputmodels.mdYou can run the following comamand get help for the command.pydantic-mermaid--helpUse in codeImport your Pydantic models into your Python script.Create an instance of the MermaidGenerator class from thepydantic-mermaidmodule and pass in your Pydantic models as arguments.frompydantic_mermaidimportMermaidGeneratorimportmy_modulegenerator=MermaidGenerator(my_module)Call the generate_chart() method of the MermaidGenerator instance to generate the Mermaid chart.chart=generator.generate_chart()Use the chart variable to display or save the Mermaid chart.print(chart)This will print the Mermaid chart as a string. You can also save the chart to a file by writing the chart string to a file:withopen("chart.mmd","w")asf:f.write(chart)This will save the Mermaid chart to a file called chart.mmd. You can then use a tool like the Mermaid Live Editor to visualize and edit the chart.examplesInheritance:classDiagram
    class Animal {
    }

    class Fish {
        gill: str
    }

    class Beast {
        lags: int
    }

    class Bird {
        winds: int
    }

    class Dog {
    }

    class Cat {
    }

    class Salmon {
    }

    class Eagle {
    }


    Animal <|-- Fish
    Animal <|-- Bird
    Animal <|-- Beast
    Beast <|-- Cat
    Beast <|-- Dog
    Fish <|-- Salmon
    Bird <|-- Eagledependencies:Administrative Divisions of the United States of AmericaclassDiagram
    class Municipality {
        name: str
        population: int
    }

    class MinorCivilDivision {
        name: str
        population: int
    }

    class County {
        name: str
        population: int
        municipalities: list[Municipality]
        minor_civil_divisions: list[MinorCivilDivision]
    }

    class CountyEquivalant {
        name: str
        population: int
    }

    class State {
        name: str
        population: int
        counties: list[County]
        county_equivalants: list[CountyEquivalant]
    }

    class FederalDistrict {
        name: str
        population: int
    }

    class InhabitedTerritory {
        name: str
        population: int
    }

    class HabitedTerritory {
        name: str
        population: int
    }

    class Federal {
        name: str
        population: int
        federal_distric: FederalDistrict
        states: list[State]
        Inhabited_territories: list[InhabitedTerritory]
        Habited_territories: list[HabitedTerritory]
    }


    County ..> MinorCivilDivision
    County ..> Municipality
    State ..> CountyEquivalant
    State ..> County
    Federal ..> InhabitedTerritory
    Federal ..> HabitedTerritory
    Federal ..> State
    Federal ..> FederalDistrictFor details, check examples/ folder.
Package: pydantic-model-parser
Pydantic Model ParserA simple package to transform/map dictionaries, before parsing it into Pydantic.RequirementsThe models/entities should conform toPydantic'sModel specifications and should inherit thepydantic.BaseModel.Installationpip3installpydantic-model-parserUsageFirstly, define your entity using Pydantic'sBaseModel.# comment.pyfrompydanticimportBaseModelclassUser(BaseModel):id:intname:strclassComment(BaseModel):id:intcomment_str:struser:UserNext, define theMapper. The mapper can be used torearrangedictionary keys andperformtransformations on the values.The tuples definitions are as follows:(old_field_path: str,new_field_path: str,transform_func: Optional[Callable])transform_funcofNonemaps the value as per the original valuetransform_funcoflambda x: x * 2maps the value as double of the original valueold_field_path's value is placed innew_field_pathin the new dictionary and subsequently parsed into theBaseModelThe.in the path delimits the nested levels in the dictionaries. e.g.user.idrefers to:{"user":{"id":1}}Defining a Mapper:# comment.pyfrommodel_parser.custom_typesimportMappingfrommodel_parser.mapperimportBaseMapperclassCommentMapper(BaseMapper):@staticmethoddefget_mapping()->List[Mapping]:return[('id','id',None),('comment_str','comment_str',None),('user_name','user.name',None),('user_id','user.id',None)]Lastly, toparseobjects:# main.pyfromcommentimportComment,CommentMapperdata={"id":1,"comment_str":"HelloWorld","user_id":2,"user_name":"bob"}data_list=[data,data]parser=Parser(Comment,CommentMapper)# parse into a Comment entitycomment=parser.parse(data)# parse into a list of Comment entitiescomments=parser.parse(data_list)
Package: pydantic-mongo
Pydantic MongoDocument object mapper for pydantic and pymongoUsageInstall:pipinstallpydantic-mongoExample CodefrombsonimportObjectIdfrompydanticimportBaseModelfrompydantic_mongoimportAbstractRepository,ObjectIdFieldfrompymongoimportMongoClientfromtypingimportListimportosclassFoo(BaseModel):count:intsize:float=NoneclassBar(BaseModel):apple:str='x'banana:str='y'classSpam(BaseModel):id:ObjectIdField=Nonefoo:Foobars:List[Bar]classSpamRepository(AbstractRepository[Spam]):classMeta:collection_name='spams'client=MongoClient("mongodb://localhost:27017")database=client["example"]spam=Spam(foo=Foo(count=1,size=1.0),bars=[Bar()])spam_with_predefined_id=Spam(id=ObjectId("611827f2878b88b49ebb69fc"),foo=Foo(count=2,size=2.0),bars=[Bar()])spam_repository=SpamRepository(database=database)# Insert / Updatespam_repository.save(spam)# Insert / Update many itemsspam_repository.save_many([spam,spam_with_predefined_id])# Deletespam_repository.delete(spam)# Find One By Idresult=spam_repository.find_one_by_id(spam.id)# Find One By Id using string if the id attribute is a ObjectIdFieldresult=spam_repository.find_one_by_id(ObjectId('611827f2878b88b49ebb69fc'))assertresult.foo.count==2# Find One By Queryresult=spam_repository.find_one_by({'foo.count':1})# Find By Queryresults=spam_repository.find_by({'foo.count':{'$gte':1}})# Paginate using cursor based paginationedges=spam_repository.paginate({'foo.count':{'$gte':1}},limit=1)more_edges=spam_repository.paginate({'foo.count':{'$gte':1}},limit=1,after=list(edges)[-1].cursor)