full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

Pydantic validation values missing

Open gtm1235 opened this issue 3 years ago • 4 comments

ntegration/backend/app/app$ python -m main.py Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 185, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/lib/python3.8/runpy.py", line 111, in _get_module_details import(pkg_name) File "/home/gtm1235/stel_project/stel_integration/backend/app/app/main.py", line 4, in from app.api.api_v1.api import api_router File "/home/gtm1235/stel_project/stel_integration/backend/app/app/api/api_v1/api.py", line 3, in from app.api.api_v1.endpoints import items, login, users, utils File "/home/gtm1235/stel_project/stel_integration/backend/app/app/api/api_v1/endpoints/items.py", line 6, in from app import crud, models, schemas File "/home/gtm1235/stel_project/stel_integration/backend/app/app/crud/init.py", line 2, in from .crud_user import user File "/home/gtm1235/stel_project/stel_integration/backend/app/app/crud/crud_user.py", line 5, in from app.core.security import get_password_hash, verify_password File "/home/gtm1235/stel_project/stel_integration/backend/app/app/core/security.py", line 7, in from app.core.config import settings File "/home/gtm1235/stel_project/stel_integration/backend/app/app/core/config.py", line 89, in settings = Settings() File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.init File "pydantic/main.py", line 331, in pydantic.main.BaseModel.init pydantic.error_wrappers.ValidationError: 10 validation errors for Settings SERVER_NAME field required (type=value_error.missing) SERVER_HOST field required (type=value_error.missing) SENTRY_DSN object of type 'NoneType' has no len() (type=type_error) POSTGRES_SERVER field required (type=value_error.missing) POSTGRES_USER field required (type=value_error.missing) POSTGRES_PASSWORD field required (type=value_error.missing) POSTGRES_DB field required (type=value_error.missing) SQLALCHEMY_DATABASE_URI can only concatenate str (not "NoneType") to str (type=type_error) FIRST_SUPERUSER field required (type=value_error.missing) FIRST_SUPERUSER_PASSWORD field required (type=value_error.missing)

Any help on while while trying to run the backend this happens? Is it supposed to pull from the root directory .env and if so how does that work? ANy help would be appreciated. Note that I was able to docker compose no problem -- well mostly no problem and I have built and deployed. Locally to develop is causing me major pain though lol.

gtm1235 avatar Jan 12 '22 23:01 gtm1235

ntegration/backend/app/app$ python -m main.py Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 185, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/lib/python3.8/runpy.py", line 111, in _get_module_details import(pkg_name) File "/home/gtm1235/stel_project/stel_integration/backend/app/app/main.py", line 4, in from app.api.api_v1.api import api_router File "/home/gtm1235/stel_project/stel_integration/backend/app/app/api/api_v1/api.py", line 3, in from app.api.api_v1.endpoints import items, login, users, utils File "/home/gtm1235/stel_project/stel_integration/backend/app/app/api/api_v1/endpoints/items.py", line 6, in from app import crud, models, schemas File "/home/gtm1235/stel_project/stel_integration/backend/app/app/crud/init.py", line 2, in from .crud_user import user File "/home/gtm1235/stel_project/stel_integration/backend/app/app/crud/crud_user.py", line 5, in from app.core.security import get_password_hash, verify_password File "/home/gtm1235/stel_project/stel_integration/backend/app/app/core/security.py", line 7, in from app.core.config import settings File "/home/gtm1235/stel_project/stel_integration/backend/app/app/core/config.py", line 89, in settings = Settings() File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.init File "pydantic/main.py", line 331, in pydantic.main.BaseModel.init pydantic.error_wrappers.ValidationError: 10 validation errors for Settings SERVER_NAME field required (type=value_error.missing) SERVER_HOST field required (type=value_error.missing) SENTRY_DSN object of type 'NoneType' has no len() (type=type_error) POSTGRES_SERVER field required (type=value_error.missing) POSTGRES_USER field required (type=value_error.missing) POSTGRES_PASSWORD field required (type=value_error.missing) POSTGRES_DB field required (type=value_error.missing) SQLALCHEMY_DATABASE_URI can only concatenate str (not "NoneType") to str (type=type_error) FIRST_SUPERUSER field required (type=value_error.missing) FIRST_SUPERUSER_PASSWORD field required (type=value_error.missing)

Any help on while while trying to run the backend this happens? Is it supposed to pull from the root directory .env and if so how does that work? ANy help would be appreciated. Note that I was able to docker compose no problem -- well mostly no problem and I have built and deployed. Locally to develop is causing me major pain though lol.

First you need change your config.py file like the following code below:

// backend/app/app/core/config.py
class Settings(BaseSettings):
    class Config:
        case_sensitive = True
        env_file = "../../.env"   // **Add this line**
        env_file_encoding = "utf-8"  // **Add this line**
    API_V1_STR: str = "/api/v1"
    # SERVER_NAME: str // **Comment this line**
    # SERVER_HOST: AnyHttpUrl // **Comment this line**
    SECRET_KEY: str = secrets.token_urlsafe(32)
    ....

Next go to the app folder by command: cd backend/app

And then install dependencies by using poetry with command poetry install

Finally run the app with command uvicorn app.main:app --reload

You could read the docs here for more details.

Work with env File: https://fastapi.tiangolo.com/advanced/settings/#reading-a-env-file Start App: https://fastapi.tiangolo.com/#run-it

vuongtlt13 avatar Apr 11 '22 10:04 vuongtlt13

I have the same issue with this code:

from typing import Any, Dict, List, Optional, Union

from pydantic import AnyHttpUrl, BaseSettings, PostgresDsn, validator


class Settings(BaseSettings):
    API_V1_STR: str = "/api/v1"
    PROJECT_NAME: str
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []

    @validator("BACKEND_CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)

    POSTGRES_SERVER: str
    POSTGRES_USER: str
    POSTGRES_PASSWORD: str
    POSTGRES_DB: str
    DATABASE_URI: Optional[PostgresDsn] = None

    @validator("DATABASE_URI", pre=True)
    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
        if isinstance(v, str):
            return v
        return PostgresDsn.build(
            scheme="postgresql",
            user=values.get("POSTGRES_USER"),
            password=values.get("POSTGRES_PASSWORD"),
            host=values.get("POSTGRES_SERVER"),
            path=f"/{values.get('POSTGRES_DB') or ''}",
        )

    class Config:
        case_sensitive = True
        env_file = ".env"


settings = Settings()

GDemay avatar Jul 25 '22 15:07 GDemay

  • host=values.get("POSTGRES_SERVER"),

Should be,

  • host=str(values.get("POSTGRES_SERVER")),

Warning is:

Argument of type "Any | None" cannot be assigned to parameter "host" of type "str" in function "build"
  Type "Any | None" cannot be assigned to type "str"
    Type "None" cannot be assigned to type "str"

Bimal2614 avatar Apr 29 '23 04:04 Bimal2614

I have the similar error for the below code can anyone help me in fixing this??

Error : File "C:\Users***\Openai_API_db_langchain.py", line 38, in db_chain = SQLDatabaseSequentialChain(llm=llm, database=db, verbose=True) File "pydantic\main.py", line 341, in pydantic.main.BaseModel.init pydantic.error_wrappers.ValidationError: 2 validation errors for SQLDatabaseSequentialChain decider_chain field required (type=value_error.missing) sql_chain field required (type=value_error.missing)

import os
from langchain import OpenAI, SQLDatabase
from langchain.chains import SQLDatabaseSequentialChain

os.environ['OPENAI_API_KEY'] = "**********************************8"

dburi = 'postgresql://postgres:******@*****:*****/*****'
db = SQLDatabase.from_uri(dburi)

llm = OpenAI(temperature=0)
db_chain = SQLDatabaseSequentialChain(llm=llm, database=db, verbose=True)

resp = db_chain.run('what is my last po value')
print(resp)

Abhiram-003 avatar Jun 01 '23 06:06 Abhiram-003