Skip to content
Snippets Groups Projects
Commit ad9eafcd authored by Antoine R. Dumont's avatar Antoine R. Dumont
Browse files

Add jsonp decorator

CLOSE T110

source: http://flask.pocoo.org/snippets/79/
parent c54fdc8c
No related branches found
Tags v0.0.5 v0.0.6 v0.0.7
No related merge requests found
......@@ -13,6 +13,7 @@ from flask import make_response
from swh.core.hashutil import ALGORITHMS
from swh.web.ui.main import app
from swh.web.ui import service, query
from swh.web.ui.decorators import jsonp
hash_filter_keys = ALGORITHMS
......@@ -287,6 +288,7 @@ def revision_at_origin(timestamp, origin_type, origin_url):
@app.route('/api/1/stat/counters')
@jsonp
def api_stats():
"""Return statistics as a JSON object"""
return jsonify(service.stat_counters())
......
# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
res = func(*args, **kwargs)
if hasattr(res, 'data'): # for a response object, data
data = res.data
if isinstance(data, bytes): # we're dealing in utf-8 bytes
data = data.decode('utf-8')
else:
data = str(data)
else: # fallback case...
data = str(res)
content = ''.join([str(callback), '(', data, ')'])
return current_app.response_class(
content,
mimetype='application/javascript')
return func(*args, **kwargs)
return decorated_function
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment