Wrap __stream into a class and define a method named close where you can write your logic. The close method will be registered in _resource_closers, and Django will call the methods in _resource_closers sequentially when the connection ends.