image-and-stash.py (1710B)
1 # This is a simple implementation of a server-side stash that supports two 2 # operations: 3 # - increment: 4 # Increments a value in the stash keyed by a given uuid, and returns an 5 # image file 6 # - read: 7 # Returns the value in the stash keyed by a given uuid or 0 otherwise. 8 # This is a read-only operation, and does not remove the value from the 9 # stash as-is the default WPT stash behavior: 10 # https://web-platform-tests.org/tools/wptserve/docs/stash.html. 11 12 import os 13 14 from wptserve.utils import isomorphic_decode 15 16 def main(request, response): 17 if b"increment" in request.GET: 18 uuid = request.GET[b"increment"] 19 20 # First, increment the stash value keyed by `uuid`, and write it back to the 21 # stash. Writing it back to the stash is necessary since `take()` actually 22 # removes the value whereas we want to increment it. 23 stash_value = request.server.stash.take(uuid) 24 if stash_value is None: 25 stash_value = 0 26 request.server.stash.put(uuid, stash_value + 1) 27 28 # Return a basic image. 29 response_headers = [(b"Content-Type", b"image/png")] 30 image_path = os.path.join(os.path.dirname(isomorphic_decode(__file__)), u"image.png") 31 return (200, response_headers, open(image_path, mode='rb').read()) 32 33 elif b"read" in request.GET: 34 uuid = request.GET[b"read"] 35 stash_value = request.server.stash.take(uuid) 36 37 if stash_value is None: 38 stash_value = 0 39 # Write the stash value keyed by `uuid` back to the stash. This is necessary 40 # because `take()` actually removes it, but we want a read-only read. 41 request.server.stash.put(uuid, stash_value); 42 return (200, [], str(stash_value)) 43 44 return (404 , [], "Not found")