Middleware return object #7964
-
|
Hi, At the moment we always get the Response back, but ideally we would like to return our own custom response and we would handle the conversion to the powertools Response in our middleware. Is there any way to make this work? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Hey! Thanks for raising this question. I may not have fully understood your question and I'm wondering if you could you share a quick code snippet of what you're trying to achieve? If you want your handler to return a custom object and convert it to from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from dataclasses import dataclass
app = APIGatewayRestResolver()
@dataclass
class MyCustomResponse:
data: dict
status: int = 200
def response_converter_middleware(app, next_middleware):
result = next_middleware(app)
# Already a Response, return as-is
if isinstance(result, Response):
return result
# Convert custom response to Powertools Response
if isinstance(result, MyCustomResponse):
return Response(
status_code=result.status,
content_type="application/json",
body=result.data,
)
# Fallback
return Response(status_code=200, body=result)
app.use([response_converter_middleware])
@app.get("/hello")
def hello():
# Return your custom object - middleware converts it
return MyCustomResponse(data={"message": "Hello!"}, status=200)The middleware wraps |
Beta Was this translation helpful? Give feedback.
-
|
Hi, we have found a way to simplify our design and this question is no longer necessary for us. |
Beta Was this translation helpful? Give feedback.
Hi, we have found a way to simplify our design and this question is no longer necessary for us.