Skip to content

Instantly share code, notes, and snippets.

@scoates
Last active September 21, 2017 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scoates/027488c39d5407bbfa125ff3f3a9a622 to your computer and use it in GitHub Desktop.
Save scoates/027488c39d5407bbfa125ff3f3a9a622 to your computer and use it in GitHub Desktop.
Asynchronous results in Zappa
from zappa.async import task, get_async_response
from flask import Flask
from time import sleep, time
app = Flask(__name__)
@app.route('/bake')
def bake():
start = time()
baking = []
for i in range(0, int(request.args.get('num', 3))):
baking.append(bake_one().response_id)
baked = {}
bake_time = 0
while True:
for b in baking:
if b in baked:
continue
response = get_async_response(b)
if response is not None and response['status'] == 'complete':
baked[b] = response['response']
bake_time = bake_time + response['response']['time']
if len(baked) == len(baking):
break # from the (while True)
else:
# not done baking all of the things
sleep(1)
elapsed = time() - start
out = "Baked {} items in {} seconds. Baking took {} seconds.\n\n".format(
len(baked), elapsed, bake_time)
for response_id, result in baked.items():
out = out + "Baked a {} in {} seconds.\n".format(
result['what'], result['time'])
return out
@task(capture_response=True)
def bake_one():
bake_time = randint(1,10)
sleep(bake_time)
return {
"what": choice(['pie', 'cake', 'casserole', 'potato']),
"time": bake_time,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment