-
-
Save NicolasT/4a443e8214c2c6eea1a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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