网页
综合
更新时间 2026-11-14 09:44:53
Middleware - Starlette
自动蜘蛛
starlette.dev
正文约 6000 字
Starlette includes several middleware classes for adding behavior that is applied across your entire application. These are all implemented as standard ASGI middleware classes, and can be applied either to Starlette or to any other ASGI application.
The Starlette application class allows you to include the ASGI middleware in a way that ensures that it remains wrapped by the exception handler.
Every Starlette application automatically includes two pieces of middleware by default:
Middleware is evaluated from top-to-bottom, so the flow of execution in our example application would look like this:
The following middleware implementations are available in the Starlette package:
Creates an OpenTelemetry server span for every incoming HTTP request. The span follows the OpenTelemetry HTTP semantic conventions, extracts distributed trace context from the request headers, and uses the matched route template for its name and http.route attribute.
OpenTelemetryMiddleware is experimental. Its API and emitted telemetry may change in minor releases without a deprecation period.
Install the optional API dependency with pip install opentelemetry-api, or as part of pip install "starlette[full]". Starlette only uses the OpenTelemetry API. Your application chooses and configures the SDK and exporter. If no tracer provider is configured, the middleware skips tracing.
Pydantic Logfire configures a global OpenTelemetry provider. Add the middleware to enable Starlette tracing:
The same applies to any standard OpenTelemetry SDK configuration:
You can create the app before you configure the global provider.
You can also wrap any ASGI application directly:
Multiple native middleware instances on the same request create only one span.
Pass a comma-separated string or a sequence of regular expressions in excluded_urls. If any expression matches the full request URL, the middleware does not create a span. This is useful for health checks, readiness probes, and other high-volume endpoints that you do not need to trace.
Adds appropriate CORS headers to outgoing responses in order to allow cross-origin requests from browsers.
The default parameters used by the CORSMiddleware implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.
The following arguments are supported:
The middleware responds to two particular types of HTTP request...
These are any OPTIONS request with Origin and Access-Control-Request-Method headers. In this case the middleware will intercept the incoming request and respond with appropriate CORS headers, and either a 200 or 400 response for informational purposes.
Any request with an Origin header. In this case the middleware will pass the request through as normal, but will include appropriate CORS headers on the response.
Private Network Access is a browser security feature that restricts websites from public networks from accessing servers on private networks.
When a website attempts to make such a cross-network request, the browser will send a Access-Control-Request-Private-Network: true header in the pre-flight request. If the allow_private_network flag is set to True, the middleware will include the Access-Control-Allow-Private-Network: true header in the response, allowing the request. If set to False, the middleware will return a 400 response, blocking the request.
When using CORSMiddleware with your Starlette application, it's important to ensure that CORS headers are applied even to error responses generated by unhandled exceptions. The recommended solution is to wrap the entire Starlette application with CORSMiddleware. This approach guarantees that even if an exception is caught by ServerErrorMiddleware (or other outer error-handling middleware), the response will still include the proper Access-Control-Allow-Origin header.
For example, instead of adding CORSMiddleware as an inner middleware via the Starlette middleware parameter, you can wrap your application as follows:
Adds signed cookie-based HTTP sessions. Session information is readable but not modifiable.
The session cookie is always set with the "HttpOnly" flag, preventing client-side JavaScript from accessing it.
Access or modify the session data using the request.session dictionary interface.
Changes to nested values are not tracked automatically. For example, request.session["cart"].append(item) does not mark the session as modified. Assign the updated value back to the session, such as request.session["cart"] = cart, to ensure the changes are saved.
The following arguments are supported:
Enforces that all incoming requests must either be https or wss. Any incoming requests to http or ws will be redirected to the secure scheme instead.
There are no configuration options for this middleware class.
Enforces that all incoming requests have a correctly set Host header, in order to guard against HTTP Host Header attacks.
The following arguments are supported:
If an incoming request does not validate correctly then a 400 response will be sent.
Limits the total size of incoming HTTP request bodies. The limit applies to the raw body bytes, including multipart file data and multipart encoding overhead. Requests that exceed the limit receive a 413 Content Too Large response.
The following argument is supported:
The middleware uses Content-Length to reject an oversized body before reading it when possible, and always counts the body bytes received from the ASGI server. This also supports requests without Content-Length and prevents an understated header from bypassing the limit.
Handles GZip responses for any request that includes "gzip" in the Accept-Encoding header.
The middleware will handle both standard and streaming responses.
On streaming responses, the middleware compresses and emits output for every chunk the application sends, so chunks reach the client as they are produced instead of waitin
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。