From 72a90cb3a0f9d82d0c62376579f439c258ef709b Mon Sep 17 00:00:00 2001 From: David Brochart Date: Wed, 30 Aug 2023 12:09:37 +0200 Subject: [PATCH] Add CLI --allow-origin (CORS) --- jupyverse_api/jupyverse_api/cli.py | 8 ++++++++ jupyverse_api/jupyverse_api/main/__init__.py | 13 ++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/jupyverse_api/jupyverse_api/cli.py b/jupyverse_api/jupyverse_api/cli.py index df1bbfa9..135f5f08 100644 --- a/jupyverse_api/jupyverse_api/cli.py +++ b/jupyverse_api/jupyverse_api/cli.py @@ -25,6 +25,12 @@ default=8000, help="The host port.", ) +@click.option( + "--allow-origin", + multiple=True, + type=str, + help="The origin to allow.", +) @click.option( "--set", "set_", @@ -44,6 +50,7 @@ def main( port: int, set_: List[str], disable: List[str], + allow_origin: List[str], ) -> None: set_ = list(set_) for i, s in enumerate(set_): @@ -51,6 +58,7 @@ def main( set_.append(f"component.open_browser={open_browser}") set_.append(f"component.host={host}") set_.append(f"component.port={port}") + set_.append(f"component.allow_origin={allow_origin}") config = get_config(disable) run.callback( unsafe=False, diff --git a/jupyverse_api/jupyverse_api/main/__init__.py b/jupyverse_api/jupyverse_api/main/__init__.py index 477aabbe..25813044 100644 --- a/jupyverse_api/jupyverse_api/main/__init__.py +++ b/jupyverse_api/jupyverse_api/main/__init__.py @@ -1,12 +1,13 @@ from __future__ import annotations import webbrowser -from typing import Any, Callable, Dict, Sequence +from typing import Any, Callable, Dict, Sequence, Tuple from asgiref.typing import ASGI3Application from asphalt.core import Component, Context from asphalt.web.fastapi import FastAPIComponent from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from ..app import App @@ -39,11 +40,21 @@ def __init__( app: FastAPI | str | None = None, host: str = "127.0.0.1", port: int = 8000, + allow_origin: Tuple = (), open_browser: bool = False, query_params: Dict[str, Any] | None = None, debug: bool | None = None, middlewares: Sequence[Callable[..., ASGI3Application] | dict[str, Any]] = (), ) -> None: + if allow_origin: + middleware = { + "type": CORSMiddleware, + "allow_origins": allow_origin, + "allow_credentials": True, + "allow_methods": ["*"], + "allow_headers": ["*"], + } + middlewares = list(middlewares) + [middleware] super().__init__( components, # type: ignore app=app,