fix
This commit is contained in:
@@ -4,10 +4,43 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from typing import Annotated, List
|
from typing import List
|
||||||
|
|
||||||
from pydantic import Field, field_validator
|
from pydantic import Field
|
||||||
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_cors_origins(raw: str) -> List[str]:
|
||||||
|
"""Parse a CORS_ORIGINS env value into a list of origin strings.
|
||||||
|
|
||||||
|
Accepts (in priority order):
|
||||||
|
- JSON array string: '["http://a","http://b"]'
|
||||||
|
- comma-separated: "http://a,http://b"
|
||||||
|
- single value: "http://a"
|
||||||
|
Strips whitespace and drops empties. Returns the default list if input
|
||||||
|
is empty/blank.
|
||||||
|
|
||||||
|
This helper exists because pydantic-settings' EnvSettingsSource treats
|
||||||
|
`List[str]` as a "complex" type and tries to JSON-decode the raw env
|
||||||
|
value BEFORE any field validator runs — so a plain comma-separated
|
||||||
|
string from docker-compose crashes Settings() at import time on
|
||||||
|
older pydantic-settings versions. Storing the field as `str` sidesteps
|
||||||
|
that entirely; this helper parses it on demand.
|
||||||
|
"""
|
||||||
|
if not raw:
|
||||||
|
return ["http://localhost:5173"]
|
||||||
|
v = raw.strip()
|
||||||
|
if not v:
|
||||||
|
return ["http://localhost:5173"]
|
||||||
|
if v.startswith("["):
|
||||||
|
import json
|
||||||
|
try:
|
||||||
|
parsed = json.loads(v)
|
||||||
|
if isinstance(parsed, list):
|
||||||
|
return [str(o).strip() for o in parsed if str(o).strip()]
|
||||||
|
except Exception:
|
||||||
|
pass # fall through to comma-split
|
||||||
|
return [o.strip() for o in v.split(",") if o.strip()]
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -32,30 +65,17 @@ class Settings(BaseSettings):
|
|||||||
admin_setup_token: str = ""
|
admin_setup_token: str = ""
|
||||||
|
|
||||||
# CORS
|
# CORS
|
||||||
# `NoDecode` tells pydantic-settings NOT to JSON-parse the env value, so a
|
# Stored as a raw string (NOT List[str]) so pydantic-settings' env source
|
||||||
# plain comma-separated string like "http://localhost:5173,http://localhost:8080"
|
# treats it as a simple scalar and never attempts JSON-decoding. The
|
||||||
# reaches our `@field_validator` intact, which then splits it into a list.
|
# parsed list is exposed via the `cors_origins_list` property below.
|
||||||
cors_origins: Annotated[List[str], NoDecode] = Field(
|
# Accepts either a comma-separated string ("http://a,http://b") or a
|
||||||
default_factory=lambda: ["http://localhost:5173"]
|
# JSON-array string ('["http://a","http://b"]').
|
||||||
)
|
cors_origins: str = "http://localhost:5173"
|
||||||
|
|
||||||
@field_validator("cors_origins", mode="before")
|
@property
|
||||||
@classmethod
|
def cors_origins_list(self) -> List[str]:
|
||||||
def _split_origins(cls, v):
|
"""Parsed list of allowed CORS origins (see `_parse_cors_origins`)."""
|
||||||
if isinstance(v, str):
|
return _parse_cors_origins(self.cors_origins)
|
||||||
# Allow both JSON arrays (e.g. '["http://a","http://b"]') and plain
|
|
||||||
# comma-separated strings (e.g. "http://a,http://b") from env vars.
|
|
||||||
v = v.strip()
|
|
||||||
if v.startswith("["):
|
|
||||||
import json
|
|
||||||
try:
|
|
||||||
return [o.strip() for o in json.loads(v) if o.strip()]
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return [o.strip() for o in v.split(",") if o.strip()]
|
|
||||||
if isinstance(v, (list, tuple)):
|
|
||||||
return [str(o).strip() for o in v if str(o).strip()]
|
|
||||||
return v
|
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
log_level: str = "INFO"
|
log_level: str = "INFO"
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ app = FastAPI(
|
|||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=settings.cors_origins,
|
allow_origins=settings.cors_origins_list,
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
|
|||||||
Reference in New Issue
Block a user