【python + flask】字典字段对模型字段的自动赋值,抽象编程思维培养,框架能力

场景:

客户端提交上来的数据

python 复制代码
# @Time      :2024-2024/2/27-10:40
# @Author    :Justin
# @Email     :[email protected]
# @file      :demo1.py
# @Software  :FisherBook

# class A():
#     def __enter__(self):
#         print("I am enter!")
#         # 这里必须要return self 否则 as b中报错
#         return self
#
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print("i am exit")
#
#     def query(self):
#         print("i am query")
#
#
# a = A()
# a.query()
# with A() as b:
#     b.query()
#
#
# class Sample:
#     def __enter__(self):
#         print("in enter!")
#         return "aaa"
#
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print("in exit")
#
#     @staticmethod
#     def get_sample():
#         return Sample()
#
#
# s = Sample()
# with s.get_sample() as sample:
#     print("sample:", sample)
from contextlib import contextmanager

# @contextmanager
import traceback


class MyResource():
    def __enter__(self):
        print("i am enter")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("i am exit")

        if exc_type:
            print(exc_type, exc_val, exc_tb)
            print(traceback.format_exc())
            raise exc_val

    def query(self, data):
        print("i am query data")


with MyResource() as r:
    r.query(data=[])

print("-------------")
from contextlib import contextmanager


@contextmanager
def make_myresource():
    print("connect to resource!")
    yield MyResource()
    print("close resource connection!")


try:
    with make_myresource() as r:
        try:
            r.query([])
        except Exception as e:
            print(traceback.format_exc())
except Exception as e:
    print(e)

from contextlib import contextmanager


@contextmanager
def book_mark():
    print("《", end="")
    yield
    print("》", end="")


with book_mark():
    print("且将生活一饮而尽", end="")
print("-----")


class C:
    @contextmanager
    def ccc(self):
        print("1111")
        yield
        print("33333")


c = C()
with c.ccc():
    print("2222")

print("==========")


# hasattr()
# setattr()
class D():
    id = None
    name = None

    def __init__(self, no=0):
        self.no = no


# 类属性也可以
d = D()
print(hasattr(d, "id"), hasattr(d, "age"), hasattr(d, "no"))

param = {
    "name": "张三",
    "age": 18,
    "gender": 1,
    "class_no": 11
    # 等等很多属性
}


class Student():
    # __slots__ = "name", "age", "gender", "class_no", "__dict__"

    pass


student = Student()
student.name = param["name"]
student.age = param["age"]
student.gender = param["gender"]
student.class_no = param["class_no"]

print(student.age, student.__dict__, student.__dir__())
# var的做法只能将构造函数里面的属性转成字典,而__dict__则范围更广
my_dict = vars(student)
print(my_dict)


class Student2():
    name = None
    age = None
    gender = None
    class_no = None

    def setattrs(self, attrs_dict: dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key):
                setattr(self, key, value)


student2 = Student2()
student2.setattrs(param)
print(vars(student2))

vars 可以将定义过的对象属性或者类属性,还原成字典。

加上slots的则不可以。

hasattr和setattr可以配对使用

也可以用内置的__setattr__(self, key, value)来处理。

2.统一处理

比如有些字段,时间则需要统一转换,或者自增id在使用时则需要隐藏,

python 复制代码
class Student2():
    name = None
    age = None
    gender = None
    class_no = None

    def __init__(self):
        self.create_time = int(datetime.now.timestamp())

    def setattrs(self, attrs_dict: dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key != "id":
                setattr(self, key, value)

上面的类作为base类,被其它实体类所继承,比如user,order... 这里假定每张表都有create_time的int类型的字段

相关推荐
南玖yy2 分钟前
C++ 成员变量缺省值:引用、const 与自定义类型的初始化规则详解,引用类型和const类型的成员变量自定义类型成员是否可以用缺省值?
c语言·开发语言·c++·后端·架构·c++基础语法
keerduoba8 分钟前
ACTF2025 - WEB Excellent-Site
经验分享·flask
大G哥22 分钟前
Java 中的 Integer 缓存池:背后的性能优化机制解析
java·开发语言·缓存·性能优化
RockLiu@80535 分钟前
探索PyTorch中的空间与通道双重注意力机制:实现concise的scSE模块
人工智能·pytorch·python
小虚竹43 分钟前
claude 3.7,极为均衡的“全能型战士”大模型,国内直接使用
开发语言·后端·claude·claude3.7
牛马baby1 小时前
Java高频面试之并发编程-11
java·开发语言·面试
huangyuchi.1 小时前
【C++11】类的新功能
开发语言·笔记·c++11·delete·移动构造·移动赋值·deflut
s9123601011 小时前
Rust std::thread::spawn(move) 的作用
开发语言·后端·rust
XWXnb61 小时前
STM32 中断系统深度剖析
c语言·开发语言·stm32·嵌入式硬件