Skip to content

Instantly share code, notes, and snippets.

@emmanuellyautomated
Created February 5, 2018 15:38
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 emmanuellyautomated/a01e7506ce96b6cd60a05cd2be076271 to your computer and use it in GitHub Desktop.
Save emmanuellyautomated/a01e7506ce96b6cd60a05cd2be076271 to your computer and use it in GitHub Desktop.
Example of a convenient way to stream generators as JSON in your flask app
import json
from flask import Response, stream_with_context
def render_as_json(generator_creating_function):
""" Decorator to render JSON from generator-creating functions
"""
def wrapper():
generated_items = generator_creating_function()
yield '{"items":['
try:
while True:
first = json.dumps(next(generated_items))
second = json.dumps(next(generated_items))
yield ','.join([first, second]) + ','
except StopIteration:
yield first
yield ']}'
return wrapper
@render_as_json
def create_generator():
""" Fill this with something that yields items or returns a generator
"""
pass
@app.route('/stream-generator', methods=['GET'])
def stream_generator():
return Response(stream_with_context(create_generator()), 200, mimetype='application/json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment