You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am looking for the appropriate way to unzip clients requests which are gzip encoded. Looking at the GZipMiddleware it seems that it only zip responses but do not care about requests.
Thus I tried to do it at the dispatch level without success. I did something like:
@app.middleware("http")asyncdefdispatch(request, call_next):
plain_body=gzip.decompress(request.body())
request._body=plain_body# I don't think it is the appropriate wayresponse=awaitcall_next(request) # hangs herereturnresponse
I am not extremely familiar with the inner-working of starlette so I don't know how to "push back in the queue" the decoded the request with the decoded body. If found no middlewares doing similar things.
Anyone can pinpoint me the appropriate way to do it ?
Your approach is close, but it won't work until you reach the endpoint call, because a new Request instance is created at each step in the middleware.
You could probably make it work via an endpoint decorator with a little elbow grease -- the request you'd receive at that point would work. (But that would mean decorators everywhere; subideal).
@tomchristie has in other issues pointed out downsides to consuming the request stream in middleware.
I think the right way to do this would actually be to override the body method on the Starlette request to look for an appropriate header, and un-gzip if appropriate. Currently this isn't especially convenient, but it is possible. You need to do the following:
Subclass starlette.requests.Request, and override the body method with the behavior you want.
Create a function that is very similar to starlette.routing.request_response, except that it uses your custom subclass of Request, rather than the starlette-builtin Request.
Create a subclass of starlette.routing.Route, and modify the __init__ to set self.app using the custom request_response from step 2. This could be done via:
(You could also just set the request._body inside your custom_request_response -- if you did that, you wouldn't need to subclass Request, but I suppose it is a private API...)
@tomchristie I think it would be nice if it were a little easier to override the Request class in a custom Route subclass -- I think this could provide an appropriate alternative to this "request-modifying" behavior that has been requested in at least a few cases.
One approach might be to add an argument request_type: Type[Request] = Request to request_response, and then have a class variable for the request_type on the Route, which gets used during the app building.
Edit: I opened a PR (#645) doing just this. I won't be offended though if the changes are undesirable/rejected for any reason.
Thank you very much for such a quick and detailed response! Nice PR I hope it will get merged soon ! As I cannot use it at the moment I tried getting it working with the hints you gave me. However I am stuck with a weird issue, here is a minimal example:
classItem(BaseModel):
foo: strbar: strclassCustomRequest(Request):
asyncdefbody(self) ->bytes:
awaitsuper().body()
ifself.headers.get("Content-Encoding") =="gzip":
self._body=gzip.decompress(self._body)
returnself._bodydefcustom_request_response(func: Callable) ->ASGIApp:
# same as starlette.routing.request_response but with CustomRequest instead of RequestclassCustomRoute(APIRoute):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
ifinspect.isfunction(self.endpoint) orinspect.ismethod(self.endpoint):
self.app=custom_request_response(self.endpoint)
# on fastapi sideapp=FastAPI()
app.router.route_class=CustomRoute@app.post("/item/")asyncdefpost_item(item: Item):
return {"foo": item.foo}
When testing with TestClient I obtain the error:
AttributeError: 'CustomRequest' object has no attribute 'foo'
Thus it looks like the endpoint post_item is receiving the CustomRequest instead of the Item.
I think I did something wrong but I can't locate where. I think we are not supposed to patch the app.router.route_class but that is the quicker way I found.
Ahh yes if you are using this with FastAPI you have to do things a little differently. Look at the implementation in the convert-msgpack-to-json issue I linked above and see if you can adapt that.
Yes indeed ! It really looks like what I want to do but with msgpack. You saved my day π. I am going to get it running and will post a running solution.
The middleware only does this for responses, because gzip encoding in HTTP is generally only applied on responses, not requests.
In a request, the client does not have any standard way of pre-determining if a server supports gzip encoded request bodies. In a response, the server has already received the client headers, and is able to determine if the client supports gzip response bodies.
Iβd be happy to see third party middleware for dealing with this, but my judgement at the moment is that itβs probably not something weβll support in the core package.
For anyone facing this issue, this comment contains a generic body-manipulating middleware that may be of interest -- in particular, it should work to handle the situation where you want to un-gzip the request body.
Related, @florimondmanca's https://github.com/florimondmanca/msgpack-asgi seems to be a more full-featured implementation of related functionality (just with msgpack encoding/decoding, rather than gzip); I think it could be adapted to work with gzip if desired.
(To be clear, I would also agree that a third party solution is probably best.)
For anyone facing this issue, this comment contains a generic body-manipulating middleware that may be of interest -- in particular, it should work to handle the situation where you want to un-gzip the request body.
Yup, though as I think I mentioned there a more full-featured approach that's just "GZipMiddleware(with gzipfile and buffering) but for requests" is probably more sane. In retrospect I really don't think any kind of generic middleware is worth it w.r.t. having the middleware do its job as good as it can possibly do. :-)
In a request, the client does not have any standard way of pre-determining if a server supports gzip encoded request bodies.
I guess the train of thought for most use cases here is when you control both the client and the server and you have built clients so that they use gzip/msgpack/etc. And in all cases, I suppose looking at the Content-Encoding header in the request might be a sane approach to detecting when a client has sent a compressed request body?
I come from a C# background, and there you can easily configure your code to decompress Requests if necessary. request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
My opinion is that this capability should be added to the core packages to ease the life of the developpers. This is a case that happens in real life (event if seldomly), in my career I have encountered 2 clients that sended their requests compressed in GZip., and I can't change these clients, it is me who should adapt to these. I am bothered to not be able to handle this with a built-in feature.
We're not preventing anyone from developing a GZipMiddleware that handles unzipping requests.
You're welcome to do so as a third party package, and we'd happily link to it from the docs.
Activity
dmontagu commentedon Sep 20, 2019
Your approach is close, but it won't work until you reach the endpoint call, because a new
Requestinstance is created at each step in the middleware.You could probably make it work via an endpoint decorator with a little elbow grease -- the request you'd receive at that point would work. (But that would mean decorators everywhere; subideal).
@tomchristie has in other issues pointed out downsides to consuming the request stream in middleware.
I think the right way to do this would actually be to override the
bodymethod on the Starlette request to look for an appropriate header, and un-gzip if appropriate. Currently this isn't especially convenient, but it is possible. You need to do the following:starlette.requests.Request, and override thebodymethod with the behavior you want.starlette.routing.request_response, except that it uses your custom subclass ofRequest, rather than the starlette-builtinRequest.starlette.routing.Route, and modify the__init__to setself.appusing the customrequest_responsefrom step 2. This could be done via:(You could also just set the
request._bodyinside yourcustom_request_response-- if you did that, you wouldn't need to subclassRequest, but I suppose it is a private API...)dmontagu commentedon Sep 20, 2019
I actually used a similar approach while helping with this question about converting msgpack to json in middleware (it's fastapi, but the same ideas are used).
@tomchristie I think it would be nice if it were a little easier to override the
Requestclass in a customRoutesubclass -- I think this could provide an appropriate alternative to this "request-modifying" behavior that has been requested in at least a few cases.One approach might be to add an argument
request_type: Type[Request] = Requesttorequest_response, and then have a class variable for the request_type on the Route, which gets used during the app building.Edit: I opened a PR (#645) doing just this. I won't be offended though if the changes are undesirable/rejected for any reason.
RobinDavid commentedon Sep 20, 2019
Thank you very much for such a quick and detailed response! Nice PR I hope it will get merged soon ! As I cannot use it at the moment I tried getting it working with the hints you gave me. However I am stuck with a weird issue, here is a minimal example:
When testing with
TestClientI obtain the error:Thus it looks like the endpoint
post_itemis receiving theCustomRequestinstead of the Item.I think I did something wrong but I can't locate where. I think we are not supposed to patch the
app.router.route_classbut that is the quicker way I found.dmontagu commentedon Sep 20, 2019
Ahh yes if you are using this with FastAPI you have to do things a little differently. Look at the implementation in the convert-msgpack-to-json issue I linked above and see if you can adapt that.
dmontagu commentedon Sep 20, 2019
@RobinDavid In particular, the implementation in this comment is the one to try to mirror.
RobinDavid commentedon Sep 20, 2019
Yes indeed ! It really looks like what I want to do but with msgpack. You saved my day π. I am going to get it running and will post a running solution.
lovelydinosaur commentedon Nov 2, 2019
The middleware only does this for responses, because gzip encoding in HTTP is generally only applied on responses, not requests.
In a request, the client does not have any standard way of pre-determining if a server supports gzip encoded request bodies. In a response, the server has already received the client headers, and is able to determine if the client supports gzip response bodies.
Iβd be happy to see third party middleware for dealing with this, but my judgement at the moment is that itβs probably not something weβll support in the core package.
dmontagu commentedon Nov 2, 2019
For anyone facing this issue, this comment contains a generic body-manipulating middleware that may be of interest -- in particular, it should work to handle the situation where you want to un-gzip the request body.
Related, @florimondmanca's https://github.com/florimondmanca/msgpack-asgi seems to be a more full-featured implementation of related functionality (just with msgpack encoding/decoding, rather than gzip); I think it could be adapted to work with gzip if desired.
(To be clear, I would also agree that a third party solution is probably best.)
florimondmanca commentedon Nov 2, 2019
Yup, though as I think I mentioned there a more full-featured approach that's just "
GZipMiddleware(with gzipfile and buffering) but for requests" is probably more sane. In retrospect I really don't think any kind of generic middleware is worth it w.r.t. having the middleware do its job as good as it can possibly do. :-)florimondmanca commentedon Nov 2, 2019
I guess the train of thought for most use cases here is when you control both the client and the server and you have built clients so that they use gzip/msgpack/etc. And in all cases, I suppose looking at the
Content-Encodingheader in the request might be a sane approach to detecting when a client has sent a compressed request body?lovelydinosaur commentedon Nov 2, 2019
True
romanmar commentedon Nov 8, 2019
Above gzip decompression code in an example:
https://github.com/romanmar/starlette-gzip-router/blob/master/gzip_router.py
saryeHaddadi commentedon Oct 19, 2021
I come from a C# background, and there you can easily configure your code to decompress Requests if necessary.
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;My opinion is that this capability should be added to the core packages to ease the life of the developpers. This is a case that happens in real life (event if seldomly), in my career I have encountered 2 clients that sended their requests compressed in GZip., and I can't change these clients, it is me who should adapt to these. I am bothered to not be able to handle this with a built-in feature.
lovelydinosaur commentedon Oct 20, 2021
We're not preventing anyone from developing a GZipMiddleware that handles unzipping requests.
You're welcome to do so as a third party package, and we'd happily link to it from the docs.
RazCrimson commentedon Jun 30, 2024
I didn't find any simple snippet or alternative package that does this, so made one.
https://github.com/RazCrimson/starlette-gzip-request
For those who don't want to add a new dependency, just feel free to use the code in here