Python flask.current_app.response_class() Examples
The following are 24
code examples of flask.current_app.response_class().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask.current_app
, or try the search function
.
Example #1
Source File: flask_sse.py From flask-sse with MIT License | 6 votes |
def stream(self): """ A view function that streams server-sent events. Ignores any :mailheader:`Last-Event-ID` headers in the HTTP request. Use a "channel" query parameter to stream events from a different channel than the default channel (which is "sse"). """ channel = request.args.get('channel') or 'sse' @stream_with_context def generator(): for message in self.messages(channel=channel): yield str(message) return current_app.response_class( generator(), mimetype='text/event-stream', )
Example #2
Source File: exporters.py From flask-restaction with MIT License | 6 votes |
def export_json(data, status, headers): """ Creates a JSON response JSON content is encoded by utf-8, not unicode escape. Args: data: any type object that can dump to json status (int): http status code headers (dict): http headers """ dumped = json.dumps(data, ensure_ascii=False) resp = current_app.response_class( dumped, status=status, headers=headers, content_type='application/json; charset=utf-8') return resp
Example #3
Source File: app.py From blog-a with MIT License | 6 votes |
def support_jsonp(f): """ Wraps JSONified output for JSONP https://gist.github.com/richardchien/7b7c2727feb3e8993845a3ce61bad808 """ @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + f(*args, **kwargs).data.decode('utf-8') + ')' return current_app.response_class(content, mimetype='application/json') else: return f(*args, **kwargs) return decorated_function
Example #4
Source File: utils.py From commandment with MIT License | 6 votes |
def plistify(*args, **kwargs): """Similar to jsonify, which ships with Flask, this function wraps plistlib.dumps and sets up the correct mime type for the response.""" if args and kwargs: raise TypeError('plistify() behavior undefined when passed both args and kwargs') elif len(args) == 1: # single args are passed directly to dumps() data = args[0] else: data = args or kwargs mimetype = kwargs.get('mimetype', current_app.config['PLISTIFY_MIMETYPE']) return current_app.response_class( (plistlib.dumps(data), '\n'), mimetype=mimetype )
Example #5
Source File: controllers.py From indico-plugins with MIT License | 6 votes |
def _process(self): config = Config() config.HTMLExporter.preprocessors = [CppHighlighter] config.HTMLExporter.template_file = 'basic' with self.attachment.file.open() as f: notebook = nbformat.read(f, as_version=4) html_exporter = HTMLExporter(config=config) body, resources = html_exporter.from_notebook_node(notebook) css_code = '\n'.join(resources['inlining'].get('css', [])) nonce = str(uuid4()) html = render_template('previewer_jupyter:ipynb_preview.html', attachment=self.attachment, html_code=body, css_code=css_code, nonce=nonce) response = current_app.response_class(html) # Use CSP to restrict access to possibly malicious scripts or inline JS csp_header = "script-src cdn.mathjax.org 'nonce-{}';".format(nonce) response.headers['Content-Security-Policy'] = csp_header response.headers['X-Webkit-CSP'] = csp_header # IE10 doesn't have proper CSP support, so we need to be more strict response.headers['X-Content-Security-Policy'] = "sandbox allow-same-origin;" return response
Example #6
Source File: api_utils.py From netman with Apache License 2.0 | 5 votes |
def json_response(data, code): json_data = json.dumps(data, indent=None) response = current_app.response_class(json_data, mimetype='application/json; charset=UTF-8') response.status_code = code return response
Example #7
Source File: app.py From Flask-aiohttp with MIT License | 5 votes |
def async_stream(): def f(): yield 'I\'m ' yield 'sorry!' yield from asyncio.sleep(1) return app.response_class(f())
Example #8
Source File: app.py From Flask-aiohttp with MIT License | 5 votes |
def stream(): def f(): yield 'Hello, ' yield 'World!' return app.response_class(f())
Example #9
Source File: app.py From Flask-aiohttp with MIT License | 5 votes |
def late(): yield from asyncio.sleep(3) data = { 'data': 'done' } data = json.dumps(data) current_app.response_class(data, headers={ 'Content-Type': 'application/json', }, status=201) return 'done'
Example #10
Source File: apispec.py From flask-unchained with MIT License | 5 votes |
def _openapi_json(self): """Serve JSON spec file""" # We don't use Flask.jsonify here as it would sort the keys # alphabetically while we want to preserve the order. from pprint import pprint pprint(self.to_dict()) return current_app.response_class(json.dumps(self.to_dict(), indent=4), mimetype='application/json')
Example #11
Source File: decorators.py From mbspotify with GNU General Public License v2.0 | 5 votes |
def jsonp(func): """Wraps JSONified output for JSONP requests.""" # Based on snippet from http://flask.pocoo.org/snippets/79/. @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype) else: return func(*args, **kwargs) return decorated_function
Example #12
Source File: __init__.py From flask-smorest with MIT License | 5 votes |
def _openapi_json(self): """Serve JSON spec file""" # We don't use Flask.jsonify here as it would sort the keys # alphabetically while we want to preserve the order. return current_app.response_class( json.dumps(self.spec.to_dict(), indent=2), mimetype='application/json')
Example #13
Source File: controllers.py From indico-plugins with MIT License | 5 votes |
def _check_access(self): from indico_storage_s3.plugin import S3StoragePlugin auth = request.authorization if not S3StoragePlugin.settings.get('bucket_info_enabled'): raise NotFound username = S3StoragePlugin.settings.get('username') password = S3StoragePlugin.settings.get('password') if not auth or not auth.password or auth.username != username or auth.password != password: response = current_app.response_class('Authorization required', 401, {'WWW-Authenticate': 'Basic realm="Indico - S3 Buckets"'}) raise Unauthorized(response=response)
Example #14
Source File: cases.py From freight with Apache License 2.0 | 5 votes |
def setUp(self): self.client = AuthenticatedTestClient(current_app, current_app.response_class) super(TransactionTestCase, self).setUp()
Example #15
Source File: cases.py From freight with Apache License 2.0 | 5 votes |
def setUp(self): self.client = AuthenticatedTestClient(current_app, current_app.response_class) super(TestCase, self).setUp()
Example #16
Source File: base.py From freight with Apache License 2.0 | 5 votes |
def client(self): return HookClient(current_app, current_app.response_class)
Example #17
Source File: __init__.py From renku-python with Apache License 2.0 | 5 votes |
def error_response(code, reason): """Construct error response.""" return current_app.response_class( response=JsonRPCResponse().dumps({ 'error': { 'code': code, 'reason': reason } }), mimetype='application/json' )
Example #18
Source File: __init__.py From renku-python with Apache License 2.0 | 5 votes |
def result_response(serializer, data): """Construct flask response.""" return current_app.response_class( response=serializer.dumps({'result': data}), mimetype='application/json' )
Example #19
Source File: serialization.py From DIVE-backend with GNU General Public License v3.0 | 5 votes |
def jsonify(obj, status=200): json_string = pjson.dumps(format_json(obj, camel_case=True)) return current_app.response_class(json_string, mimetype='application/json', status=status) # Custom AMQP json encoding # http://stackoverflow.com/questions/21631878/celery-is-there-a-way-to-write-custom-json-encoder-decoder # Encoder function
Example #20
Source File: api.py From isthislegit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_actions(): """ Returns the possible actions configured on the system. """ return current_app.response_class( json.dumps([ action.to_dict(domain=g.domain, user=g.user) for action in actions ]), mimetype='application/json')
Example #21
Source File: ttype.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def token(ttype=None): """ This is a special token function. Each token type can define an additional API call, that does not need authentication on the REST API level. :return: Token Type dependent """ tokenc = get_token_class(ttype) res = tokenc.api_endpoint(request, g) serial = getParam(request.all_data, "serial") user = get_user_from_param(request.all_data) g.audit_object.log({"success": 1, "user": user.login, "realm": user.realm, "serial": serial, "token_type": ttype}) if res[0] == "json": return jsonify(res[1]) elif res[0] in ["html", "plain"]: return current_app.response_class(res[1], mimetype="text/{0!s}".format(res[0])) elif len(res) == 2: return current_app.response_class(json.dumps(res[1]), mimetype="application/{0!s}".format(res[0])) else: return current_app.response_class(res[1], mimetype="application/octet-binary", headers=res[2])
Example #22
Source File: views.py From planespotter with MIT License | 4 votes |
def jsonpify(*args, **kw): """Passes the specified arguments directly to :func:`jsonify` with a status code of 200, then wraps the response with the name of a JSON-P callback function specified as a query parameter called ``'callback'`` (or does nothing if no such callback function is specified in the request). If the keyword arguments include the string specified by :data:`_HEADERS`, its value must be a dictionary specifying headers to set before sending the JSONified response to the client. Headers on the response will be overwritten by headers specified in this dictionary. If the keyword arguments include the string specified by :data:`_STATUS`, its value must be an integer representing the status code of the response. Otherwise, the status code of the response will be :http:status:`200`. """ # HACK In order to make the headers and status code available in the # content of the response, we need to send it from the view function to # this jsonpify function via its keyword arguments. This is a limitation of # the mimerender library: it has no way of making the headers and status # code known to the rendering functions. headers = kw.pop(_HEADERS, {}) status_code = kw.pop(_STATUS, 200) response = jsonify(*args, **kw) callback = request.args.get('callback', False) if callback: # Reload the data from the constructed JSON string so we can wrap it in # a JSONP function. data = json.loads(response.data) # Force the 'Content-Type' header to be 'application/javascript'. # # Note that this is different from the mimetype used in Flask for JSON # responses; Flask uses 'application/json'. We use # 'application/javascript' because a JSONP response is valid # Javascript, but not valid JSON. headers['Content-Type'] = 'application/javascript' # Add the headers and status code as metadata to the JSONP response. meta = _headers_to_json(headers) if headers is not None else {} meta['status'] = status_code inner = json.dumps(dict(meta=meta, data=data)) content = '{0}({1})'.format(callback, inner) # Note that this is different from the mimetype used in Flask for JSON # responses; Flask uses 'application/json'. We use # 'application/javascript' because a JSONP response is not valid JSON. mimetype = 'application/javascript' response = current_app.response_class(content, mimetype=mimetype) # Set the headers on the HTTP response as well. if headers: set_headers(response, headers) response.status_code = status_code return response
Example #23
Source File: patch.py From white with GNU General Public License v2.0 | 4 votes |
def jsonify(value): """Creates a :class:`~flask.Response` with the JSON representation of the given arguments with an `application/json` mimetype. The arguments to this function are the same as to the :class:`dict` constructor. Example usage:: from flask import jsonify class User(object): def __json__(self): return dict(username=g.user.username, email=g.user.email, id=g.user.id) @app.route('/_get_current_user') def get_current_user(): return jsonify(user) This will send a JSON response like this to the browser:: { "username": "admin", "email": "admin@localhost", "id": 42 } For security reasons only objects are supported toplevel. For more information about this, have a look at :ref:`json-security`. This function's response will be pretty printed if it was not requested with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false. """ indent = None if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \ and not request.is_xhr: indent = 2 return current_app.response_class(dumps(value, indent=indent), mimetype='application/json')
Example #24
Source File: indicators.py From bearded-avenger with Mozilla Public License 2.0 | 4 votes |
def get(self): filters = {} for f in VALID_FILTERS: if request.args.get(f): filters[f] = request.args.get(f) if request.args.get('q'): filters['indicator'] = request.args.get('q') if request.args.get('confidence'): filters['confidence'] = request.args.get('confidence') if request.args.get('provider'): filters['provider'] = request.args.get('provider') if request.args.get('group'): filters['group'] = request.args.get('group') if request.args.get('tags'): filters['tags'] = request.args.get('tags') if request.args.get('lasttime'): filters['lasttime'] = request.args.get('lasttime') if current_app.config.get('dummy'): r = DummyClient(remote, pull_token()).indicators_search(filters) return jsonify_success(r) try: with Client(remote, pull_token()) as cli: r = cli.indicators_search(filters, decode=False) except RuntimeError as e: logger.error(e) return jsonify_unknown(msg='search failed') except InvalidSearch as e: return jsonify_unknown(msg='invalid search', code=400) except AuthError: return jsonify_unauth() except Exception as e: logger.error(e) return jsonify_unknown(msg='search failed, system may be too busy, check back later') response = current_app.response_class(r, mimetype='application/json') if isinstance(r, basestring): if '"message":"unauthorized"' in r and '"message":"unauthorized"' in r: response.status_code = 401 return response return response