Comments (8)
Middleware are always called, also in Starlette. Why shouldn't they run for an Options
request?
As for the order of middlewares, this is the pertinent code:
def build_middleware_stack(
self,
user_middleware: List[Union[Middleware, Type[BaseHTTPMiddleware], Type[MiddlewareProtocol]]],
allowed_hosts: Optional[List[str]],
cors_config: Optional[CORSConfig],
) -> ASGIApp:
"""
Builds the middleware stack by passing middlewares in a specific order
"""
current_app: ASGIApp = self.asgi_router
if allowed_hosts:
current_app = TrustedHostMiddleware(app=current_app, allowed_hosts=allowed_hosts)
if cors_config:
current_app = CORSMiddleware(app=current_app, **cors_config.dict())
for middleware in user_middleware:
if isinstance(middleware, Middleware):
current_app = middleware.cls(app=current_app, **middleware.options)
else:
current_app = middleware(app=current_app)
return current_app
from litestar.
See my log, for Options
request TrustedHostMiddleware
is not called, because CORSMiddleware
returns response.
For example what is the sense to run auth middleware for Options
request or before host check?
from litestar.
Look how Starlette calls middlewares
///server error middleware called
///cors middleware called
INFO: 127.0.0.1:53186 - "OPTIONS /api/a/brands HTTP/1.1" 200 OK
# here OPTIONS ends and POST starts
///server error middleware called
///cors middleware called
///trusted host middleware called///
////some middleware called
////some middleware2 called
///exception middleware called
INFO: 127.0.0.1:53186 - "POST /api/a/brands HTTP/1.1" 405 Method Not Allowed
and Starlette app
async def brand(request):
return JSONResponse({'hello': 'brand'})
class SomeMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
print('////some middleware called')
return await call_next(request)
print('////some middleware awaited')
middlewares = [
Middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=('GET', 'POST')),
Middleware(TrustedHostMiddleware, allowed_hosts=['localhost']),
Middleware(SomeMiddleware),
Middleware(SomeMiddleware2),
]
app = Starlette(
debug=True,
middleware=middlewares,
routes=[
Route('/api/a/brands', brand),
]
)
Also Starlette provide ExceptionMiddleware
where I can catch validation errors and not break CORSMiddleware
from litestar.
Lets keep this thread ordered.
- You are saying the order of middlewares is incorrect, and the logging you posted above appears to support this. The simplest course of action I can suggest is that you submit a PR. Either with a fix for the issue if you identify it, or with a failing test case that demonstrates this, use the
@xfail
decorator so the test actually passes. - The starlette app you created has a different order of middlewares than the one baked into
Starlite
. Starlite, as you can see in the code snippet I posted previously, places trusted hosts before theCORSMiddleware
. There is nothing stopping you from using the StarletteCORSMiddleware
and/orTrustedHostMiddleware
on your own and not use the builtin Starlite configurations. Is there an issue doing this? If you think thatCORSMiddleware
shoulds be called before theTrustedHostMiddleware
, please give me a compelling reason why this is so. Its not a big adjustment to do.
from litestar.
Despite the fact that in Starlie TrustedHostMiddleware
is placed before the CORSMiddleware
, as you can see in my log for Starlite CORSMiddleware
is called first. But for these two middlewares any order is fine I think. As TrustedHostMiddleware
does not return any useful data in the body.
But if some middleware returns data in the body which client app needs to read it is important to call this middleware after CORSMiddleware
from litestar.
Added PR #105
from litestar.
Thanks for your contribution! v1.3.0 has been released with your fixes.
from litestar.
Great! Thanks.
from litestar.
Related Issues (20)
- docs: remove extra test func in test client fixture example
- Enhancement: Add 3.13 matrix
- Enhancement: Resource representation response based on `Accept` header HOT 6
- Bug: Unexpected openapi type in typescript generation HOT 2
- Bug: schema generation crashes in 2.7.1 HOT 3
- Bug: default not generated for query parameter in openapi spec. HOT 9
- Bug: Path parameters missing from OpenAPI schema when not included in handler signature HOT 2
- Enhancement(Infra): Docs preview link in first message HOT 2
- Enhancement: simplify type of response_headers in AppConfig HOT 3
- Docs: Create an example of utilizing GraphQL with Litestar via Strawberry
- bug: Plugin "Flash Messages" not working with "Redirect" Response HOT 7
- Bug: App launching fails because of Pydantic version handling problem HOT 4
- Bug: In 2.8.0, openapi triggers an ImproperlyConfiguredException HOT 9
- Enhancement: Serve openapi routes under multiple path prefixes HOT 3
- Bug: cannot start server with `PydanticPlugin` if using `pydantic == 1.x.x` HOT 2
- Bug: DTO doesn't work with Generic tuples
- Documentation: Consider depth of introductory State usage document
- Bug: pydantic version logic breaks with latest pydantic HOT 2
- Bug: Remove use of `assert` for pydantic import flow control HOT 3
- Docs: Update `usage/security/guards` chapter HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from litestar.