0

I am getting an sqlalchemy.orm.exc.DetachedInstanceError error when loading the response body in a Middleware, because its response has a relationship.

code:

    async def _get_body_response(self, response):
        response_body = [chunk async for chunk in response.body_iterator]
        response_body.body_iterator = self.async_iterator_wrapper(response_body)

        try:
            body_bytes = response_body[0].decode()
        except UnicodeDecodeError:
            body_bytes = response_body[0]

        return await self._get_body(body_bytes)

error when defining response_body: sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Model1 at 0xffff9f1fff40> is not bound to a Session; lazy load operation of attribute 'relationship_1' cannot proceed (Background on this error at: https://sqlalche.me/e/14/bhk3)

I've tried to add "lazy='subquery'" to Model1.relationship_1 and it doesnt work

  • Does this answer your question? [FastAPI - How to get the response body in Middleware](https://stackoverflow.com/questions/71882419/fastapi-how-to-get-the-response-body-in-middleware) – Chris Apr 04 '23 at 18:13
  • Cris, no =x My problem is when I am processing '[chunk async for chunk in response.body_iterator]'. This raises an error DetachedInstanceError. I am not able to generate the response body because my Model1 has an attribute which is a relationship – Guilherme Lacerda Apr 04 '23 at 18:42

0 Answers0