utils.py (1277B)
1 import datetime 2 import json 3 import time 4 5 6 def _url_dir(request): 7 return u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/' 8 9 10 def store_request_timing_and_headers(request): 11 """Store the current timestamp and request's headers in the stash object of 12 the server. The request must a GET request and must have the "id" parameter. 13 """ 14 id = request.GET.first(b"id") 15 timestamp = datetime.datetime.now().timestamp() 16 17 value = { 18 "timestamp": timestamp, 19 "headers": request.raw_headers, 20 } 21 22 url_dir = _url_dir(request) 23 request.server.stash.put(id, value, url_dir) 24 25 26 def get_request_timing_and_headers(request, id=None): 27 """Get previously stored timestamp and request headers associated with the 28 given "id". When "id" is not given the id is retrieved from "request". 29 """ 30 if id is None: 31 id = request.GET.first(b"id") 32 url_dir = _url_dir(request) 33 item = request.server.stash.take(id, url_dir) 34 if not item: 35 return None 36 return json.dumps(item) 37 38 39 def wait_for_preload_to_finish(request, id): 40 """Wait until a preload associated with "id" is sent.""" 41 while True: 42 if get_request_timing_and_headers(request, id): 43 break 44 time.sleep(0.1) 45 time.sleep(0.1)