[Python] Pydantic function: assemble_cors_origins does not work as intented

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am having some problems with CORS in local deployment using Pydantic and FastAPI. It's a weird problem, because on how I import the domains on which I allow CORS, it works or not.

    ERROR OBTAINED


    Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
    ​

    When allowing all possible domains to be able requesting I don't have any problem:

    if settings.BACKEND_CORS_ORIGINS:

    app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )


    The following code is the one I am currently using, and after doing debug I know that everything seems to be fine. And it works.

    BACKEND_CORS_ORIGINS = ast.literal_eval(os.getenv("BACKEND_CORS_ORIGINS", "[]"))

    if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
    CORSMiddleware,
    allow_origins=BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )


    The problem is when I do the following, that is the way I am requested to do it:

    if settings.BACKEND_CORS_ORIGINS:
    BACKEND_CORS_ORIGINS =[str(origin) for origin in settings.BACKEND_CORS_ORIGINS]

    app.add_middleware(
    CORSMiddleware,
    allow_origins=BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )


    where the variable settings is located in the config.py file and has the following in-built function:

    # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins
    # e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", "http://localhost:8080"]'
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl]
    @field_validator("BACKEND_CORS_ORIGINS", mode="before")
    @classmethod
    def assemble_cors_origins(cls, value: Union[str, List[str]]) -> Union[List[str], str]:
    backend_cors_origins = None
    if isinstance(value, str) and not value.startswith("["):
    backend_cors_origins = [i.strip() for i in value.split(",")]
    elif isinstance(value, (list, str)):
    backend_cors_origins = value
    if backend_cors_origins:
    return backend_cors_origins
    raise ValueError(value)


    I have tried to do debug here, and the output list seems to be correct. That's why I don't understand what is happening.

    Continue reading...

Compartilhe esta Página