How to wait for a successful response to the client?

One of the services that is integrated into my app uses request cancellation. If this happens after the database transaction is closed, after the return response.json(...) line from the controller, then the transaction is not rolled back.

How can I make the transaction to be completed only after a successful response to the client, or hang handler to cancel the request by the client?

This is dependent upon your dB driver. Please provide a snippet.

I use gino(async sqlalchemy).

def example_controller(request):
    async with db.transaction() as tx:
        ...some code...
        return response.json(...)

This is exactly what I would do. If they cancel for example in response Middleware, that’s kind of the client’s fault. But, you could alternatively use signals to start your transaction and wait for the response signal to close it. That should incorporate the entire life cycle.

Thanks! I think signals are what will help me. Haven’t seen this before.

1 Like

Another option might be to stream the response. Then you control when and how bytes are sent to the client.