dispatcher.py (1995B)
1 import json 2 from wptserve.utils import isomorphic_decode 3 4 # A server used to store and retrieve arbitrary data. 5 # This is used by: ./dispatcher.js 6 def main(request, response): 7 # This server is configured so that is accept to receive any requests and 8 # any cookies the web browser is willing to send. 9 response.headers.set(b"Access-Control-Allow-Credentials", b"true") 10 response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') 11 response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') 12 response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin") or '*') 13 14 if b"cacheable" in request.GET: 15 response.headers.set(b"Cache-Control", b"max-age=31536000") 16 else: 17 response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate') 18 19 # CORS preflight 20 if request.method == u'OPTIONS': 21 return b'' 22 23 uuid = request.GET[b'uuid'] 24 stash = request.server.stash; 25 26 # The stash is accessed concurrently by many clients. A lock is used to 27 # avoid unterleaved read/write from different clients. 28 with stash.lock: 29 queue = stash.take(uuid, '/common/dispatcher') or []; 30 31 # Push into the |uuid| queue, the requested headers. 32 if b"show-headers" in request.GET: 33 headers = {}; 34 for key, value in request.headers.items(): 35 headers[isomorphic_decode(key)] = isomorphic_decode(request.headers[key]) 36 headers = json.dumps(headers); 37 queue.append(headers); 38 ret = b''; 39 40 # Push into the |uuid| queue, the posted data. 41 elif request.method == u'POST': 42 queue.append(request.body) 43 ret = b'done' 44 45 # Pull from the |uuid| queue, the posted data. 46 else: 47 if len(queue) == 0: 48 ret = b'not ready' 49 else: 50 ret = queue.pop(0) 51 52 stash.put(uuid, queue, '/common/dispatcher') 53 return ret;