Search code examples
pythonpython-3.xfastapipydantic

pydantic BaseModel not found in Fastapi


I have 3.6.9 on Kubuntu 18.04. I have installed using pip3 install fastapi. I'm trying to test drive the framework through its official documentation and I'm in the relational database section of its guide.

In schemas.py:

from typing import List

from pydantic import BaseModel

class VerseBase(BaseModel):
    AyahText: str
    NormalText: str

class Verse(VerseBase):
    id: int

    class Config:
        orm_mode = True

VS code highlights an error in from pydantic import BaseModel and it tells that: No name 'BaseModel' in module 'pydantic'. Additionally, when I try to run uvicorn main:app reload I have gotten the following error:

File "./main.py", line 6, in <module>
   from . import crud, models, schemas
ImportError: attempted relative import with no known parent package

I have tried to renstall pydantic using pip3 but it tells me that:

Requirement already satisfied: dataclasses>=0.6; python_version < "3.7" in ./.local/lib/python3.6/site-packages (from pydantic) (0.7)

Solution

  • The problem of highlighting in VS code may be a problem due to the fact that you did not open the folder. It's quite annoying as it happens often to me as well (and I have basically your same config).

    Regarding the second problem you mention, it is probably due to the fact that the folder in which the script lays, does not have a __init__.py file. If you add it, it should work since python will interpret the folder as a module.

    As an alternative, you could try to import with the full path from the top folder (e.g. from app.module.main import app).

    For more information about modules see the following links:

    Python 3.8 Modules

    Real Python