@@ -22,13 +22,15 @@ class CustomJsonSchemaGenerator(GenerateJsonSchema):
2222 def core_schema_schema (self , core_schema : core_schema .CoreSchema ) -> JsonSchemaValue :
2323 # Handle aws-lambda-powertools types that Pydantic can't process by default
2424 if isinstance (core_schema , core_schema .IsInstanceSchema ):
25- if 'CaseInsensitiveDict' in str (core_schema .cls ) or 'Cookie' in str (core_schema .cls ):
25+ cls_name = str (core_schema .cls )
26+ if 'CaseInsensitiveDict' in cls_name or 'Cookie' in cls_name :
2627 return {'type' : 'object' }
2728
2829 # Fallback to the default behavior for all other types
2930 return super ().core_schema_schema (core_schema )
3031
3132
33+
3234def is_pydantic_model (obj ):
3335 """Checks if an object is a Pydantic model class, excluding BaseModel itself."""
3436 return inspect .isclass (obj ) and issubclass (obj , BaseModel ) and obj is not BaseModel
@@ -139,6 +141,30 @@ def generate_dto_schemas(source_dir: Path, output_dir: Path, project_root: Path)
139141 model_class .update_forward_refs ()
140142 rebuilt_models_count += 1
141143 models_for_schema_gen .append ((model_class , model_name , module_name ))
144+ except NameError as e :
145+ # Attempt to handle undefined forward references dynamically
146+ match = re .search (r"name '(\w+)' is not defined" , str (e ))
147+ if match :
148+ undefined_name = match .group (1 )
149+ rprint (f" [yellow]Undefined name '{ undefined_name } ' found. Creating a dummy class to resolve forward reference.[/yellow]" )
150+ dummy_class = type (undefined_name , (dict ,), {})
151+ module = sys .modules [module_name ]
152+ setattr (module , undefined_name , dummy_class )
153+
154+ # Retry rebuilding the model
155+ try :
156+ if hasattr (model_class , "model_rebuild" ):
157+ model_class .model_rebuild (force = True )
158+ elif hasattr (model_class , "update_forward_refs" ):
159+ model_class .update_forward_refs ()
160+ rebuilt_models_count += 1
161+ models_for_schema_gen .append ((model_class , model_name , module_name ))
162+ except Exception as e_retry :
163+ rprint (f" [red]Error rebuilding model { module_name } .{ model_name } after creating dummy class: { e_retry } [/red]" )
164+ models_for_schema_gen .append ((model_class , model_name , module_name ))
165+ else :
166+ rprint (f" [red]Error rebuilding model { module_name } .{ model_name } : { e } [/red]" )
167+ models_for_schema_gen .append ((model_class , model_name , module_name ))
142168 except Exception as e :
143169 rprint (f" [red]Error rebuilding model { module_name } .{ model_name } : { e } [/red]" )
144170 models_for_schema_gen .append ((model_class , model_name , module_name ))
0 commit comments