Skip to content

Instantly share code, notes, and snippets.

@NicolasT
Created May 14, 2012 18:06
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 NicolasT/4a443e8214c2c6eea1a5 to your computer and use it in GitHub Desktop.
Save NicolasT/4a443e8214c2c6eea1a5 to your computer and use it in GitHub Desktop.
import json
import functools
import flask
APP = flask.Flask(__name__)
def stream(*args, **kwargs):
def wrapper(f):
@functools.wraps(f)
def wrapped(*a, **kw):
return flask.Response(f(*a, **kw), *args, **kwargs)
return wrapped
return wrapper
def jsonify(f):
@stream(
content_type='application/json',
headers={
'Cache-Control': 'no-cache',
})
@functools.wraps(f)
def wrapped(*args, **kwargs):
res = f(*args, **kwargs)
for chunk in json.JSONEncoder().iterencode(res):
yield chunk
return wrapped
@APP.route('/ok1')
@stream()
def ok1():
yield 'o'
yield 'k'
yield '1'
@APP.route('/ok2')
@stream()
def ok2():
def f():
yield 'ok'
yield '2'
return f()
@APP.route('/ok3')
@jsonify
def ok3():
return 'ok3'
@APP.route('/not-ok1')
@stream()
def not_ok1():
a = flask.url_for('ok3')
yield 'a = '
yield a
@APP.route('/not-ok2')
@jsonify
def not_ok2():
a = flask.url_for('ok3')
return [a]
def main():
APP.run(debug=True)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment