LitServe icon indicating copy to clipboard operation
LitServe copied to clipboard

Feature: Pass custom middlewares to the app

Open lorenzomassimiani opened this issue 1 year ago • 3 comments

🚀 Feature

Add a parameter "middlewares" to the LitServer class that takes a list of fastapi middlewares that will be assigned to the self.app.

Motivation

It is useful to enrich the fastapi app with custom middlewares, for example for metrics updates. Similarly it can be done for exception handlers.

lorenzomassimiani avatar Aug 27 '24 14:08 lorenzomassimiani

sounds good. do you want to contribute?

aniketmaurya avatar Aug 27 '24 14:08 aniketmaurya

@lorenzomassimiani awesome idea. submit a PR and we'll help you land it!

williamFalcon avatar Aug 27 '24 15:08 williamFalcon

Additional Context: Need for passing CORSMiddleware

A user reported an issue on Discord where he was unable to call the LitServe API from his frontend application due to CORS (Cross-Origin Resource Sharing) restrictions.

Passing the CORS middleware would resolve this issue, allowing the API to be accessed without being blocked.

image

bhimrazy avatar Aug 29 '24 14:08 bhimrazy

Temporary Workaround: In the meantime, here's a quick hack to resolve the CORS issue (adding any middleware) until this feature is officially integrated:

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

bhimrazy avatar Aug 29 '24 15:08 bhimrazy

Now that LitServer accepts middleware as argument, users can do the following for CORS support:

api = ls.examples.SimpleLitAPI()
server = ls.LitServer(api, middlewares=[(CORSMiddleware, {"allow_origins": ["*"], "allow_credentials": True, "allow_methods": ["*"], "allow_headers": ["*"]})])

aniketmaurya avatar Aug 30 '24 11:08 aniketmaurya