summary refs log tree commit diff
path: root/synapse/rest/media/v1
diff options
context:
space:
mode:
authorErik Johnston <erik@matrix.org>2018-01-12 13:32:03 +0000
committerErik Johnston <erik@matrix.org>2018-01-12 13:32:03 +0000
commit85a4d78213f6987c920043532bca428bb582a46b (patch)
tree7e3aa2e41824c75121eafc85c7898007ce1ddaad /synapse/rest/media/v1
parentAdd missing class var (diff)
downloadsynapse-85a4d78213f6987c920043532bca428bb582a46b.tar.xz
Make Responder a context manager
Diffstat (limited to 'synapse/rest/media/v1')
-rw-r--r--synapse/rest/media/v1/_base.py14
-rw-r--r--synapse/rest/media/v1/media_storage.py5
2 files changed, 10 insertions, 9 deletions
diff --git a/synapse/rest/media/v1/_base.py b/synapse/rest/media/v1/_base.py
index 03df875b44..1145904aeb 100644
--- a/synapse/rest/media/v1/_base.py
+++ b/synapse/rest/media/v1/_base.py
@@ -144,15 +144,16 @@ def respond_with_responder(request, responder, media_type, file_size, upload_nam
         return
 
     add_file_headers(request, media_type, file_size, upload_name)
-    yield responder.write_to_consumer(request)
+    with responder:
+        yield responder.write_to_consumer(request)
     finish_request(request)
 
 
 class Responder(object):
     """Represents a response that can be streamed to the requester.
 
-    Either `write_to_consumer` or `cancel` must be called to clean up any open
-    resources.
+    Responder is a context manager which *must* be used, so that any resources
+    held can be cleaned up.
     """
     def write_to_consumer(self, consumer):
         """Stream response into consumer
@@ -165,9 +166,10 @@ class Responder(object):
         """
         pass
 
-    def cancel(self):
-        """Called when the responder is not going to be used after all.
-        """
+    def __enter__(self):
+        pass
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
         pass
 
 
diff --git a/synapse/rest/media/v1/media_storage.py b/synapse/rest/media/v1/media_storage.py
index 49d2b7cd45..b6e7a19e12 100644
--- a/synapse/rest/media/v1/media_storage.py
+++ b/synapse/rest/media/v1/media_storage.py
@@ -220,8 +220,7 @@ class FileResponder(Responder):
 
     @defer.inlineCallbacks
     def write_to_consumer(self, consumer):
-        with self.open_file:
-            yield FileSender().beginFileTransfer(self.open_file, consumer)
+        yield FileSender().beginFileTransfer(self.open_file, consumer)
 
-    def cancel(self):
+    def __exit__(self, exc_type, exc_val, exc_tb):
         self.open_file.close()