mirror of
https://github.com/fastapi/full-stack-fastapi-template.git
synced 2026-11-03 20:36:27 +00:00
♻️ Simplify CORS configuration (#2429)
## AI Disclaimer Using Codex with gpt-5.6-sol. Reviewed manually.
This commit is contained in:
committed by
GitHub
parent
781b283849
commit
d85803bf64
@@ -1,9 +1,7 @@
|
|||||||
import warnings
|
import warnings
|
||||||
from typing import Annotated, Any, Literal, Self
|
from typing import Literal, Self
|
||||||
|
|
||||||
from pydantic import (
|
from pydantic import (
|
||||||
AnyUrl,
|
|
||||||
BeforeValidator,
|
|
||||||
EmailStr,
|
EmailStr,
|
||||||
HttpUrl,
|
HttpUrl,
|
||||||
PostgresDsn,
|
PostgresDsn,
|
||||||
@@ -13,14 +11,6 @@ from pydantic import (
|
|||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
def parse_cors(v: Any) -> list[str] | str:
|
|
||||||
if isinstance(v, str) and not v.startswith("["):
|
|
||||||
return [i.strip() for i in v.split(",") if i.strip()]
|
|
||||||
elif isinstance(v, list | str):
|
|
||||||
return v
|
|
||||||
raise ValueError(v)
|
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(
|
model_config = SettingsConfigDict(
|
||||||
# Use top level .env file (one level above ./backend/)
|
# Use top level .env file (one level above ./backend/)
|
||||||
@@ -35,17 +25,6 @@ class Settings(BaseSettings):
|
|||||||
FRONTEND_HOST: str = "http://localhost:5173"
|
FRONTEND_HOST: str = "http://localhost:5173"
|
||||||
FASTAPI_ENV: Literal["development"] | None = None
|
FASTAPI_ENV: Literal["development"] | None = None
|
||||||
|
|
||||||
BACKEND_CORS_ORIGINS: Annotated[
|
|
||||||
list[AnyUrl] | str, BeforeValidator(parse_cors)
|
|
||||||
] = []
|
|
||||||
|
|
||||||
@computed_field # type: ignore[prop-decorator]
|
|
||||||
@property
|
|
||||||
def all_cors_origins(self) -> list[str]:
|
|
||||||
return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [
|
|
||||||
self.FRONTEND_HOST
|
|
||||||
]
|
|
||||||
|
|
||||||
PROJECT_NAME: str
|
PROJECT_NAME: str
|
||||||
SENTRY_DSN: HttpUrl | None = None
|
SENTRY_DSN: HttpUrl | None = None
|
||||||
POSTGRES_SERVER: str
|
POSTGRES_SERVER: str
|
||||||
|
|||||||
+7
-9
@@ -24,15 +24,13 @@ app = FastAPI(
|
|||||||
generate_unique_id_function=custom_generate_unique_id,
|
generate_unique_id_function=custom_generate_unique_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Set all CORS enabled origins
|
app.add_middleware(
|
||||||
if settings.all_cors_origins:
|
CORSMiddleware,
|
||||||
app.add_middleware(
|
allow_origins=[settings.FRONTEND_HOST],
|
||||||
CORSMiddleware,
|
allow_credentials=True,
|
||||||
allow_origins=settings.all_cors_origins,
|
allow_methods=["*"],
|
||||||
allow_credentials=True,
|
allow_headers=["*"],
|
||||||
allow_methods=["*"],
|
)
|
||||||
allow_headers=["*"],
|
|
||||||
)
|
|
||||||
|
|
||||||
app.include_router(api_router, prefix=settings.API_V1_STR)
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
app.frontend("/", directory=FRONTEND_DIR)
|
app.frontend("/", directory=FRONTEND_DIR)
|
||||||
|
|||||||
@@ -55,7 +55,6 @@ services:
|
|||||||
restart: true
|
restart: true
|
||||||
environment:
|
environment:
|
||||||
PROJECT_NAME: ${PROJECT_NAME:?Variable not set}
|
PROJECT_NAME: ${PROJECT_NAME:?Variable not set}
|
||||||
BACKEND_CORS_ORIGINS: ${BACKEND_CORS_ORIGINS:-}
|
|
||||||
SECRET_KEY: ${SECRET_KEY:?Variable not set}
|
SECRET_KEY: ${SECRET_KEY:?Variable not set}
|
||||||
FIRST_SUPERUSER: ${FIRST_SUPERUSER:?Variable not set}
|
FIRST_SUPERUSER: ${FIRST_SUPERUSER:?Variable not set}
|
||||||
FIRST_SUPERUSER_PASSWORD: ${FIRST_SUPERUSER_PASSWORD:?Variable not set}
|
FIRST_SUPERUSER_PASSWORD: ${FIRST_SUPERUSER_PASSWORD:?Variable not set}
|
||||||
|
|||||||
@@ -75,7 +75,6 @@ export FIRST_SUPERUSER_PASSWORD="$(python -c 'import secrets; print(secrets.toke
|
|||||||
You can set several other environment variables:
|
You can set several other environment variables:
|
||||||
|
|
||||||
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
|
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
|
||||||
* `BACKEND_CORS_ORIGINS`: A list of additional allowed CORS origins separated by commas. The frontend served by FastAPI uses the same origin and doesn't need to be added.
|
|
||||||
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
|
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
|
||||||
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
|
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
|
||||||
* `SMTP_USER`: The SMTP server user to send emails.
|
* `SMTP_USER`: The SMTP server user to send emails.
|
||||||
|
|||||||
Reference in New Issue
Block a user