Просмотр исходного кода

feat(module): pydantic show list of arguments

huangrunheng 2 лет назад
Родитель
Сommit
19e8bf509d
4 измененных файлов с 116 добавлено и 29 удалено
  1. 27 20
      module/config/config_model.py
  2. 4 4
      tasks/Component/config_base.py
  3. 1 3
      tasks/Component/config_scheduler.py
  4. 84 2
      tasks/Duel/config.py

+ 27 - 20
module/config/config_model.py

@@ -221,7 +221,7 @@ class ConfigModel(ConfigBase):
 
 
         :return:
         :return:
         """
         """
-        self.write_json(self.config_name, self.dict())
+        self.write_json(self.config_name, self.model_dump())
 
 
     @staticmethod
     @staticmethod
     def type(key: str) -> str:
     def type(key: str) -> str:
@@ -284,21 +284,20 @@ class ConfigModel(ConfigBase):
             logger.warning(f'{task} is no inexistence')
             logger.warning(f'{task} is no inexistence')
             return {}
             return {}
 
 
-        def properties_groups(sch) -> dict:
-            properties = {}
-            for key, value in sch["properties"].items():
-                properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
-            return properties
-
         def extract_groups(sch):
         def extract_groups(sch):
             # 从schema 中提取未解析的group的数据
             # 从schema 中提取未解析的group的数据
-            properties = properties_groups(sch)
+            # properties = properties_groups(sch)
+            results = {}
+            properties = {}
+            for key, value in sch["properties"].items():
+                if 'items' in value:
+                    properties[key] = re.search(r"/([^/]+)$", value['items']['$ref']).group(1)
+                else:
+                    properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
 
 
-            result = {}
             for key, value in properties.items():
             for key, value in properties.items():
-                result[key] = sch["$defs"][value]
-
-            return result
+                results[key] = sch["$defs"][value]
+            return results
 
 
         def merge_value(groups, jsons, definitions) -> list[dict]:
         def merge_value(groups, jsons, definitions) -> list[dict]:
             # 将 groups的参数,同导出的json一起合并, 用于前端显示
             # 将 groups的参数,同导出的json一起合并, 用于前端显示
@@ -321,13 +320,17 @@ class ConfigModel(ConfigBase):
                 result.append(item)
                 result.append(item)
             return result
             return result
 
 
-        schema = task.model_json_schema(mode='serialization')
-        # print(schema)
+        schema = task.model_json_schema()
         groups = extract_groups(schema)
         groups = extract_groups(schema)
+        groups_value = groups.copy()
 
 
         result: dict[str, list] = {}
         result: dict[str, list] = {}
         for key, value in task.model_dump().items():
         for key, value in task.model_dump().items():
-            result[key] = merge_value(groups[key], value, schema["$defs"])
+            if key not in groups:
+                for group_name in groups.keys():
+                    if group_name in key:
+                        groups_value[key] = groups[group_name]
+            result[key] = merge_value(groups_value[key], value, schema["$defs"])
 
 
         return result
         return result
 
 
@@ -361,9 +364,15 @@ class ConfigModel(ConfigBase):
 
 
         task_object = getattr(self, task, None)
         task_object = getattr(self, task, None)
         group_object = getattr(task_object, group, None)
         group_object = getattr(task_object, group, None)
+        if group_object is None:  # deal list
+            matchs = re.findall(r'\d+', group)
+            index = int(matchs[-1]) - 1 if matchs else None
+            task_object_list = list(dict(task_object))
+            for k, v in dict(task_object).items():
+                if k not in group:
+                    continue
+                group_object = v[index] if group_object is None else None
         argument_object = getattr(group_object, argument, None)
         argument_object = getattr(group_object, argument, None)
-        # print(group_object)
-        # print(argument_object)
 
 
         if argument_object is None:
         if argument_object is None:
             logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
             logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
@@ -422,6 +431,4 @@ if __name__ == "__main__":
         print(e)
         print(e)
         c = ConfigModel()
         c = ConfigModel()
 
 
-    import json
-    sch = json.dumps(c.script_task('Duel'), indent=4)
-    print(sch)
+    c.script_set_arg('Duel', 'test_list_2', 'switch_all_soul', 'false')

+ 4 - 4
tasks/Component/config_base.py

@@ -48,23 +48,23 @@ def time_validator(v: Any) -> time:
 
 
 
 
 MultiLine = Annotated[str,
 MultiLine = Annotated[str,
-                      WithJsonSchema({'type': 'multi_line'}, mode='serialization'),]
+                      WithJsonSchema({'type': 'multi_line'}),]
 
 
 
 
 TimeDelta = Annotated[timedelta,
 TimeDelta = Annotated[timedelta,
                       BeforeValidator(datadelta_validator),
                       BeforeValidator(datadelta_validator),
                       PlainSerializer(format_timedelta, return_type=str),
                       PlainSerializer(format_timedelta, return_type=str),
-                      WithJsonSchema({'type': 'time_delta'}, mode='serialization'),]
+                      WithJsonSchema({'type': 'time_delta'}),]
 
 
 DateTime = Annotated[datetime,
 DateTime = Annotated[datetime,
                      BeforeValidator(datetime_validator),
                      BeforeValidator(datetime_validator),
                      PlainSerializer(lambda v: v.isoformat(), return_type=str),
                      PlainSerializer(lambda v: v.isoformat(), return_type=str),
-                     WithJsonSchema({'type': 'date_time'}, mode='serialization'),]
+                     WithJsonSchema({'type': 'date_time'}),]
 
 
 Time = Annotated[time,
 Time = Annotated[time,
                  BeforeValidator(time_validator),
                  BeforeValidator(time_validator),
                  PlainSerializer(lambda v: v.isoformat(), return_type=str),
                  PlainSerializer(lambda v: v.isoformat(), return_type=str),
-                 WithJsonSchema({'type': 'time'}, mode='serialization'),]
+                 WithJsonSchema({'type': 'time'}),]
 
 
 # ---------------------------------------------------------------------------------------------------------------------
 # ---------------------------------------------------------------------------------------------------------------------
 class ConfigBase(BaseModel):
 class ConfigBase(BaseModel):

+ 1 - 3
tasks/Component/config_scheduler.py

@@ -28,8 +28,6 @@ if __name__ == "__main__":
     }
     }
     s = Scheduler(**dict_s)
     s = Scheduler(**dict_s)
     print(s.model_dump())
     print(s.model_dump())
-    # schema = s.model_json_schema(mode='validation')
-    import json
-    # print(str(schema))
+
 
 
 
 

+ 84 - 2
tasks/Duel/config.py

@@ -1,8 +1,14 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
-from pydantic import BaseModel, Field
-from datetime import time
+from typing import Any, Dict
+from pydantic import (Field,
+                      model_validator,
+                      ValidationError,
+                      model_serializer,
+                      WithJsonSchema,
+                      SerializerFunctionWrapHandler,
+                      GetJsonSchemaHandler)
 
 
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.config_base import ConfigBase, Time
@@ -26,4 +32,80 @@ class DuelConfig(ConfigBase):
 class Duel(ConfigBase):
 class Duel(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     scheduler: Scheduler = Field(default_factory=Scheduler)
     duel_config: DuelConfig = Field(default_factory=DuelConfig)
     duel_config: DuelConfig = Field(default_factory=DuelConfig)
+    test_list: list[DuelConfig]
 
 
+    @model_validator(mode='before')
+    @classmethod
+    def check_list(cls, data: dict) -> Any:
+        if 'test_list' not in data:
+            data['test_list'] = []
+        for key, value in data.items():
+            if isinstance(value, list):
+                continue
+            if 'test_list' not in key:
+                continue
+            try:
+                DuelConfig(**value)
+                data['test_list'].append(value)
+            except ValidationError as e:
+                pass
+        # 补全list
+        while len(data['test_list']) < data['scheduler']['priority']:
+            data['test_list'].append(DuelConfig())
+        return data
+
+    @model_serializer()
+    def serializer_model(self, value: Any) -> Dict[str, Any]:
+        properties = self.__dict__
+        data = {}
+        for key,value in properties.items():
+            if isinstance(value, list):
+                for index, v in enumerate(value):
+                    data[f'{key}_{index+1}'] = v.model_dump()
+            else:
+                data[key] = value.model_dump()
+        return data
+
+
+if __name__ == "__main__":
+    test_dict = {
+        'scheduler': {'enable': False,
+                      'next_run': '2023-01-01T00:00:00',
+                      'priority': 5,
+                      'success_interval': '01 00:00:00',
+                      'failure_interval': '01 00:00:00',
+                      'server_update': '09:00:00',
+                      'float_time': '00:00:00'
+                      },
+        'duel_config': {'switch_all_soul': False,
+                        'limit_time': '00:30:00',
+                        'target_score': 2000,
+                        'honor_full_exit': False,
+                        'green_enable': False,
+                        'green_mark': 'green_left1'},
+        # 'test_list': [
+        #     {'switch_all_soul': True,
+        #      'limit_time': '00:30:00',
+        #      'target_score': 2000,
+        #      'honor_full_exit': False,
+        #      'green_enable': False,
+        #      'green_mark': 'green_left1'},
+        # ],
+        # 'duel_config1': {'switch_all_soul': False,
+        #                 'limit_time': '00:30:00',
+        #                 'target_score': 2000,
+        #                 'honor_full_exit': False,
+        #                 'green_enable': False,
+        #                 'green_mark': 'green_left1'},
+        # 'duel_config2': {'switch_all_soul': False,
+        #                  'limit_time': '00:30:00',
+        #                  'target_score': 2000,
+        #                  'honor_full_exit': False,
+        #                  'green_enable': False,
+        #                  'green_mark': 'green_left1'},
+
+    }
+    import json
+    c = Duel(**test_dict)
+    # print(c.model_dump_json(indent=2))
+    print(json.dumps(c.model_json_schema(), indent=2))