fastapi_client icon indicating copy to clipboard operation
fastapi_client copied to clipboard

forward_refs updates not running in all classes that need it

Open agostof opened this issue 3 years ago • 4 comments

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()

agostof avatar Jun 07 '21 02:06 agostof

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.

colindjk avatar Jul 06 '21 21:07 colindjk

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 avatar Jul 06 '21 21:07 agostof

@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

pndiku avatar Jul 14 '21 07:07 pndiku

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

pndiku avatar Nov 18 '21 16:11 pndiku