Feat/http middleware - #89
Merged
Merged
Conversation
Contributor
|
👋 Thanks for your contribution, @NEFORCEO! Please make sure:
Maintainers will review it soon. |
Contributor
Merging this PR will improve performance by 41.42%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_response_req_text_from_json |
213.2 µs | 134.7 µs | +58.28% |
| ⚡ | test_response_repr |
196.4 µs | 133.7 µs | +46.88% |
| ⚡ | test_response_property_access |
194.5 µs | 133.7 µs | +45.45% |
| ⚡ | test_response_creation |
201.3 µs | 139.3 µs | +44.44% |
| ⚡ | test_response_json_parsing |
205.6 µs | 143.5 µs | +43.28% |
| ⚡ | test_middleware_after_response |
403.1 µs | 352.7 µs | +14.29% |
Tip
Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.
Comparing feat/http-middleware (6bcf0d0) with master (6f3d441)1
Footnotes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🚀 Description
Adds
@app.middleware("http")— a function-based middleware decorator, FastAPI-style, as an alternative to subclassingBaseMiddleware.The decorated function receives
(request: Request, call_next)and wraps the entire per-request pipeline (retries, redirects, existing class-basedBaseMiddleware, the route handler) in a single coroutine — everything beforeawait call_next(request)runs before the request is sent, everything after runs once the response (orNone, on failure) comes back. Multiple registered middleware nest like a stack, first registered = outermost.A new
Requestclass (fasthttp/request.py, exported asfasthttp.Request) represents the outgoing request:.method,.url(httpx.URL),.host, mutable.headers, read-only.query_params/.json/.contentsnapshots,.route,.app, and.state(aSimpleNamespacescratch space for passing data from beforecall_nextto after it).Only
"http"is supported for now —@app.graphqland@app.wsdon't run throughHTTPClientat all (GraphQL builds its ownhttpx.AsyncClientinternally, WebSocket connects directly viawebsockets.connect), soapp.middleware("ws")/app.middleware("graphql")raiseValueErrorrather than silently doing nothing.Implementation notes
HTTPClient.send()gained an optionalextra_headerskwarg, merged into the request config before class-based middleware runs — this is howrequest.headersmutations from function middleware actually reach the outgoing request.FastHTTP._run_route()builds thecall_nextchain around the existingself.client.send(...)call site — the only placeHTTPClient.sendis invoked — so class-basedBaseMiddleware, retries, and redirects are untouched.CallNext/HTTPMiddlewareFunctype aliases live infasthttp/types.py(TYPE_CHECKING-only,Request/Responseimported there only for typing to avoid circular imports)..json/.content/.query_paramsonRequestare intentionally read-only:HTTPClient._execute_requestalready reads the body straight fromroute.json/route.data/route.filesrather than from the mutable config dict, so mutating them wouldn't affect what's sent — same pre-existing limitationBaseMiddleware.request()'skwargs["json"]already has today. Documented rather than silently misleading.🧩 Type of Change
✅ Checklist
🔗 Related Issues
Fixes #
📸 Additional Context
Tests (
tests/test_app.py::TestFastHTTPMiddlewareDecorator, 5 new):middleware_typecall_nextare preservedouter:before → inner:before → inner:after → outer:after)call_nextshort-circuits the request entirely (client.requestnever called)Docs: new tutorial page
docs/{en,ru}/tutorial/middleware/function.md(linked from the middleware nav andmiddleware/index.md), plus anapp.middleware()/Requestsection indocs/{en,ru}/reference/middleware.md.mkdocs buildpasses clean, no new broken links.Full suite:
577 passed, 1 skipped.ruff checkclean on all touched files.