Skip to content

Instantly share code, notes, and snippets.

@scoates scoates/async-app.py
Last active Sep 21, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.