solara icon indicating copy to clipboard operation
solara copied to clipboard

adding CORS middleware

Open havok2063 opened this issue 1 year ago • 0 comments

What's the best way to add FastAPI CORS middleware to solara? I tried two approaches

Method 1

Adding in the following code at the module level results in a circular import error

import solara
import solara.server.fastapi
from fastapi.middleware.cors import CORSMiddleware

solara.server.fastapi.app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])

@solara.component
def Page():
    with solara.Column():
        solara.Info("Hello")
        solara.Button("Button")

Page()

Error:

  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/server/starlette.py", line 47, in <module>
    from . import app as appmod
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/server/app.py", line 407, in <module>
    apps["__default__"] = AppScript(os.environ.get("SOLARA_APP", "solara.website.pages:Page"))
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/server/app.py", line 69, in __init__
    app = self._execute()
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/server/app.py", line 116, in _execute
    routes = [solara.autorouting._generate_route_path(self.path, first=True, initial_namespace=initial_namespace)]
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/autorouting.py", line 507, in _generate_route_path
    module = source_to_module(subpath, initial_namespace=initial_namespace)
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/autorouting.py", line 37, in source_to_module
    exec(ast, mod.__dict__)
  File "/Users/Brian/Work/solara/test2.py", line 3, in <module>
    import solara.server.fastapi
  File "/Users/Brian/anaconda3/envs/jdaviz/lib/python3.10/site-packages/solara/server/fastapi.py", line 5, in <module>
    app = FastAPI(routes=starlette.routes)
AttributeError: partially initialized module 'solara.server.starlette' has no attribute 'routes' (most likely due to a circular import). Did you mean: 'Route'?

Method 2

Adding in the code within the Page component doesn't throw any errors but does not add the CORS to the app.

import solara
from fastapi.middleware.cors import CORSMiddleware


@solara.component
def Page():
    import solara.server.fastapi
    solara.server.fastapi.app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])

    with solara.Column():
        solara.Info("Hello")
        solara.Button("Button")


Page()

havok2063 avatar Jan 23 '24 21:01 havok2063