当前位置:   article > 正文

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

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

场景:

客户端提交上来的数据

# @Time      :2024-2024/2/27-10:40
# @Author    :Justin
# @Email     :514422868@qq.com
# @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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174

vars 可以将定义过的对象属性或者类属性,还原成字典。
加上slots的则不可以。
hasattr和setattr可以配对使用
也可以用内置的__setattr__(self, key, value)来处理。

2.统一处理

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

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/166710
推荐阅读
相关标签
  

闽ICP备14008679号