Coverage for downtify/http_etag.py: 98%

41 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Answer ``304 Not Modified`` to repeat reads of large JSON listings. 

2 

3The browser keeps these responses and asks again with ``If-None-Match`` 

4(``no-cache`` means "keep it, but check first"), so a Library page whose 

5data hasn't changed downloads nothing instead of megabytes of JSON. The tag 

6hashes the body, so it needs no bookkeeping and two accounts that see 

7different rows never share one; ``private`` keeps them out of shared caches. 

8""" 

9 

10from __future__ import annotations 

11 

12import hashlib 

13from collections.abc import Collection 

14 

15from starlette.datastructures import Headers, MutableHeaders 

16from starlette.types import ASGIApp, Message, Receive, Scope, Send 

17 

18CACHE_CONTROL = 'private, no-cache' 

19 

20 

21class JsonETagMiddleware: 

22 """Tag ``GET`` responses of *paths*; other requests pass straight on.""" 

23 

24 def __init__(self, app: ASGIApp, paths: Collection[str]) -> None: 

25 self.app = app 

26 self.paths = frozenset(paths) 

27 

28 async def __call__( 

29 self, scope: Scope, receive: Receive, send: Send 

30 ) -> None: 

31 if ( 

32 scope['type'] != 'http' 

33 or scope['method'] != 'GET' 

34 or scope['path'] not in self.paths 

35 ): 

36 await self.app(scope, receive, send) 

37 return 

38 

39 start: Message = {} 

40 body = bytearray() 

41 

42 async def capture(message: Message) -> None: 

43 nonlocal start 

44 if message['type'] == 'http.response.start': 

45 start = message 

46 return 

47 body.extend(message.get('body', b'')) 

48 if message.get('more_body'): 

49 return 

50 await _send_tagged(scope, start, bytes(body), send) 

51 

52 await self.app(scope, receive, capture) 

53 

54 

55async def _send_tagged( 

56 scope: Scope, start: Message, body: bytes, send: Send 

57) -> None: 

58 """Send the buffered response, or a 304 when the browser has it.""" 

59 

60 if start['status'] != 200: 

61 await send(start) 

62 await send({'type': 'http.response.body', 'body': body}) 

63 return 

64 digest = hashlib.blake2b(body, digest_size=16).hexdigest() 

65 etag = f'"{digest}"' 

66 if Headers(scope=scope).get('if-none-match') == etag: 

67 await send({ 

68 'type': 'http.response.start', 

69 'status': 304, 

70 'headers': [ 

71 (b'etag', etag.encode()), 

72 (b'cache-control', CACHE_CONTROL.encode()), 

73 ], 

74 }) 

75 await send({'type': 'http.response.body', 'body': b''}) 

76 return 

77 headers = MutableHeaders(raw=list(start['headers'])) 

78 headers['ETag'] = etag 

79 headers['Cache-Control'] = CACHE_CONTROL 

80 await send({**start, 'headers': headers.raw}) 

81 await send({'type': 'http.response.body', 'body': body})