Skip to content

GZipMiddleware (unzipping encoded requests)Β #644

Closed

Description

@RobinDavid

Dear maintainers,

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")
async def dispatch(request, call_next):
    plain_body = gzip.decompress(request.body())
    request._body = plain_body  # I don't think it is the appropriate way
    response = await call_next(request)  # hangs here
    return response

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 ?

Thank you in advance for your help πŸ˜‰

Activity

  1. dmontagu commented on Sep 20, 2019

    @dmontagu
    Contributor

    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:

    1. Subclass starlette.requests.Request, and override the body method with the behavior you want.
    2. 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.
    3. 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:
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if inspect.isfunction(endpoint) or inspect.ismethod(endpoint):
                self.app = custom_request_response(endpoint)

    (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...)

  2. dmontagu commented on Sep 20, 2019

    @dmontagu
    Contributor

    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 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.

  3. RobinDavid commented on Sep 20, 2019

    @RobinDavid
    Author

    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:

    class Item(BaseModel):
        foo: str
        bar: str
    
    class CustomRequest(Request):
        async def body(self) -> bytes:
            await super().body()
            if self.headers.get("Content-Encoding") == "gzip":
                self._body = gzip.decompress(self._body)
            return self._body
    
    def custom_request_response(func: Callable) -> ASGIApp:
        # same as starlette.routing.request_response but with CustomRequest instead of Request
        
    class CustomRoute(APIRoute):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if inspect.isfunction(self.endpoint) or inspect.ismethod(self.endpoint):
                self.app = custom_request_response(self.endpoint)
    
    # on fastapi side
    app = FastAPI()
    app.router.route_class = CustomRoute
    
    @app.post("/item/")
    async def post_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.

  4. dmontagu commented on Sep 20, 2019

    @dmontagu
    Contributor

    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.

  5. dmontagu commented on Sep 20, 2019

    @dmontagu
    Contributor

    @RobinDavid In particular, the implementation in this comment is the one to try to mirror.

  6. RobinDavid commented on Sep 20, 2019

    @RobinDavid
    Author

    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.

  7. lovelydinosaur commented on Nov 2, 2019

    @lovelydinosaur

    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.

  8. dmontagu commented on Nov 2, 2019

    @dmontagu
    Contributor

    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.)

  9. florimondmanca commented on Nov 2, 2019

    @florimondmanca
    Contributor

    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. :-)

  10. florimondmanca commented on Nov 2, 2019

    @florimondmanca
    Contributor

    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?

  11. lovelydinosaur commented on Nov 2, 2019

    @lovelydinosaur

    True

  12. romanmar commented on Nov 8, 2019

    @romanmar
  13. saryeHaddadi commented on Oct 19, 2021

    @saryeHaddadi

    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.

  14. lovelydinosaur commented on Oct 20, 2021

    @lovelydinosaur

    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.

  15. RazCrimson commented on Jun 30, 2024

    @RazCrimson

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions