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.18.tar.gz (33.8 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.18-py3-none-any.whl (39.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: wmain-2.0.18.tar.gz
  • Upload date:
  • Size: 33.8 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.18.tar.gz
Algorithm Hash digest
SHA256 08c11291bf4b45b626f5ebed915c9516e3ca7df8a945bdb3e7c834d1bca5cb62
MD5 09f1933d37a7dc800cf47a5720afb175
BLAKE2b-256 e450fb94d5dfb127b48ce548f59726ee358d8134b8926863435d9be06c27fc16

See more details on using hashes here.

File details

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

File metadata

  • Download URL: wmain-2.0.18-py3-none-any.whl
  • Upload date:
  • Size: 39.8 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.18-py3-none-any.whl
Algorithm Hash digest
SHA256 f2f1ac26e0c0e0dc592623ad0b556e363808896454007fe87c9cc204a964ba4e
MD5 4347980fce6f7cef6ce1867bf80f8990
BLAKE2b-256 c1f65c5cd42190a73936e8888cdf06cdbc5b8e6bd57dd80978d8e6bf79ee5c06

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