Skip to main content

Python 工具集合

Project description

一. common.utils.models.LooseModel

描述: 别名基类

1. 解决问题:

在如下结构中

from pydantic import BaseModel
class User(BaseModel):
    user_id: int

即使定义了alias_generator, 也只是model的user_id的别名,但是无法改变初始化时传入的参数名称,比如有些api可能有些接口传递了userId, 有些接口传递的是userID,这种同一个平台的接口返回的同一字段大小写不一致的情况很难考虑周全

2. 设计思路

设计了一个LooseModel,通过model_config的alias_generator 把user_id转换成userid,在LooseModel的from_any_dict中将输入的字典所有的键小写去掉下划线,不管是userId还是userID 或者是user_ID, 都会变成userid,这样就可以模糊匹配到model中

3. 使用方式

from wmain.common.models import LooseModel

class Person(LooseModel):
    age: int
    s_name: str
    s_id: int

class Teacher(Person):
    students: list[Person]

dic = {
    "age": 18,
    "s_name": "张三",
    "S_Id": 1,
    "students": [
        {
            "age": 18,
            "SName": "张三",
            "SID": 1
        }
    ]
}
model = Teacher.from_any_dict(dic)
print(model)

输出

age=18 s_name='张三' s_id=1 students=[Person(age=18, s_name='张三', s_id=1)]

4. 注意事项

本模块会模糊匹配所有输入键,因此不能同时存在userID和userId这种字母一致的键

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wmain-2.0.17.tar.gz (31.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

wmain-2.0.17-py3-none-any.whl (38.0 kB view details)

Uploaded Python 3

File details

Details for the file wmain-2.0.17.tar.gz.

File metadata

  • Download URL: wmain-2.0.17.tar.gz
  • Upload date:
  • Size: 31.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.0 Windows/11

File hashes

Hashes for wmain-2.0.17.tar.gz
Algorithm Hash digest
SHA256 66eb9d8abdd326493f0ace628b4ff7cffb1ca03d126a4ba29800ad2f147191df
MD5 e151ca8710322f36b173ee6a0fa194e6
BLAKE2b-256 05783e1311b758b285b3ccf0c1e4ac978b534d6c7a96eac230f2c2511983ed33

See more details on using hashes here.

File details

Details for the file wmain-2.0.17-py3-none-any.whl.

File metadata

  • Download URL: wmain-2.0.17-py3-none-any.whl
  • Upload date:
  • Size: 38.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.0 Windows/11

File hashes

Hashes for wmain-2.0.17-py3-none-any.whl
Algorithm Hash digest
SHA256 9f42764a811c6313ff20fa28530e762c61aed133a66255628c84448077c22ea5
MD5 e473d5cc60a7602267f1e221aa9a84de
BLAKE2b-256 cd8b1fd521a1cc55ee170411bbb589b498993a3ae71f8281a2dd4f104dad450e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page