5
5
from starlette .datastructures import Headers , MutableHeaders
6
6
from starlette .types import ASGIApp , Message , Receive , Scope , Send
7
7
8
+ DEFAULT_EXCLUDED_CONTENT_TYPES = ("text/event-stream" ,)
9
+
8
10
9
11
class GZipMiddleware :
10
12
def __init__ (self , app : ASGIApp , minimum_size : int = 500 , compresslevel : int = 9 ) -> None :
@@ -30,6 +32,7 @@ def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> N
30
32
self .initial_message : Message = {}
31
33
self .started = False
32
34
self .content_encoding_set = False
35
+ self .content_type_is_excluded = False
33
36
self .gzip_buffer = io .BytesIO ()
34
37
self .gzip_file = gzip .GzipFile (mode = "wb" , fileobj = self .gzip_buffer , compresslevel = compresslevel )
35
38
@@ -46,7 +49,8 @@ async def send_with_gzip(self, message: Message) -> None:
46
49
self .initial_message = message
47
50
headers = Headers (raw = self .initial_message ["headers" ])
48
51
self .content_encoding_set = "content-encoding" in headers
49
- elif message_type == "http.response.body" and self .content_encoding_set :
52
+ self .content_type_is_excluded = headers .get ("content-type" , "" ).startswith (DEFAULT_EXCLUDED_CONTENT_TYPES )
53
+ elif message_type == "http.response.body" and (self .content_encoding_set or self .content_type_is_excluded ):
50
54
if not self .started :
51
55
self .started = True
52
56
await self .send (self .initial_message )
0 commit comments