fastapi_client
fastapi_client copied to clipboard
forward_refs updates not running in all classes that need it
When running a simple example client I get the following error:
pydantic.errors.ConfigError: field "status" not yet prepared so type is still a ForwardRef,
you might need to call Metadata.update_forward_refs().
It seems that the initialization code in client/__init__.py
is not finding all the classes that need the fwd_refs to be updated.
My solution was to run update_forward_refs in all classes (openapi-python-templates/__init__package.mustache
)
for model in inspect.getmembers(models, inspect.isclass):
if model[1].__module__ == "client.models":
model_class = model[1]
if isinstance(model_class, BaseModel) or hasattr(model_class, "update_forward_refs"):
model_class.update_forward_refs()
I tried changing isinstance
to issubclass
and it worked.
The reason is b/c isinstance
will always return false. The model_class
isn't an instance of the BaseModel, it's a class itself that subclasses BaseModel.
That sounds good. To be honest, I did my patch keeping as much of the original code (e.g. isinstance()) as possible. And in this case the assumption was that the "update_forward_refs" property was available to be called which is what I tested for.
@agostof when I try your fix I get an error:
File "pydantic/main.py", line 832, in pydantic.main.BaseModel.update_forward_refs
File "pydantic/typing.py", line 382, in pydantic.typing.update_field_forward_refs
File "pydantic/typing.py", line 62, in pydantic.typing.evaluate_forwardref
File "/usr/lib64/python3.8/typing.py", line 518, in _evaluate
eval(self.__forward_code__, globalns, localns),
File "<string>", line 1, in <module>
NameError: name 'IO' is not defined
If anyone is still looking into using this, then the proper patch is this:
Edit file openapi-python-templates/__init__package.mustache
if model[1].__module__ == "@[email protected]":
model_class = model[1]
if isinstance(model_class, BaseModel) or hasattr(model_class, "update_forward_refs"):
try:
model_class.update_forward_refs()
except Exception:
pass