How to use the flask.make_response function in Flask

To help you get started, we’ve selected a few Flask examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hammerlab / seltest / seltest / proxy.py View on Github external
# TODO: fix this; we want a content-length
    if headers.get('content-length'):
        del headers['content-length']
    is_html_response = 'text/html' in headers.get('content-type', '')
    def resp_iter():
        is_first_chunk = True
        for chunk in response.iter_content(CHUNK_SIZE):
            # TODO: Possible bug: '
github hpe-storage / python-3parclient / test / HPE3ParMockServer_flask.py View on Github external
if 'setmembers' not in host_set:
                        host_set['setmembers'] = []
                    if member not in host_set['setmembers']:
                        host_set['setmembers'].extend(members)
                    else:
                        throw_error(409, HOST_IN_SET,
                                    "The object is already part of the set")
                elif 2 == data['action']:
                    # 2 is memRemove- Removes a member from the set
                    for member in members:
                        host_set['setmembers'].remove(member)
                else:
                    throw_error(400, INV_INPUT_BAD_ENUM_VALUE,
                                desc='invalid input: bad enum value - action')

        resp = flask.make_response(json.dumps(host_set), 200)
        return resp

    throw_error(404, NON_EXISTENT_SET, "host set doesn't exist")
github obscuritylabs / OS-CFDB / .site / cfdb-api / api.py View on Github external
Decorators:
        app.route -- Flask route
        cache.cached -- Redis view cache
        limiter.limit --limt route per IP to 120 a min.

    Returns:
        json -- list of finding data.
    """
    try:
        temp = []
        f_id = '^' + str(request.args.get('id'))
        cursor = db.findings.find({"finding.findingDetails.findingMatrix.id": {
                                  "$regex": f_id}}, {"_id": True, 'finding.findingDetails.findingMatrix': True}).limit(10)
        for x in cursor:
            temp.append({'id': str(x['_id']), 'data': x['finding']})
        return make_response(jsonify(temp), 200)
    except:
        abort(500)
github lyft / amundsenfrontendlibrary / amundsen_application / api / metadata / v0.py View on Github external
"""
    try:
        url = app.config['METADATASERVICE_BASE'] + TAGS_ENDPOINT
        response = request_metadata(url=url)
        status_code = response.status_code

        if status_code == HTTPStatus.OK:
            message = 'Success'
            tags = response.json().get('tag_usages')
        else:
            message = 'Encountered error: Tags Unavailable'
            logging.error(message)
            tags = []

        payload = jsonify({'tags': tags, 'msg': message})
        return make_response(payload, status_code)
    except Exception as e:
        message = 'Encountered exception: ' + str(e)
        payload = jsonify({'tags': [], 'msg': message})
        logging.exception(message)
        return make_response(payload, HTTPStatus.INTERNAL_SERVER_ERROR)
github arkii / docker-registry-ui / docker-registry-ui.py View on Github external
def add_http_header(object=None, key=None, value=None):
    _response = make_response(object)
    _response.headers[key] = value
    return _response
github trondhindenes / Flauthority / flauthority / api_generatecertificate.py View on Github external
curr_user = auth.username()

        task_timeout = appconfig['task_timeout']
        task_obj = {
            'subject_name': subject_name,
            'cert_extension': cert_extension,
            'validity_days': str(cert_lifetime_days)
        }

        allow_cert_extension = appconfig['allow_cert_extension']
        allow = [x for x in allow_cert_extension if x.strip() == cert_extension]
        if len(allow) == 0:
            logger.warning(str.format("Template requested: {1}, allowed extension: {1}", cert_extension,
                                      str(allow_cert_extension)))
            return make_response("Invalid cert extension", 400)

        task_result = celery_runner.generate_certificate.apply_async([task_obj], soft=task_timeout, hard=task_timeout)
        result = {'task_id': task_result.id}
        return result
github quay / quay / endpoints / web.py View on Github external
def opensearch():
    template = render_template(
        "opensearch.xml",
        baseurl=get_app_url(),
        registry_title=app.config.get("REGISTRY_TITLE", "Quay"),
    )
    resp = make_response(template)
    resp.headers["Content-Type"] = "application/xml"
    return resp
github DOAJ / doaj / portality / search.py View on Github external
info['api_key'] = acc.data['api_key']
                    info['_created'] = acc.data['_created']
                    info['collection'] = acc.data['collection']
                    info['owner'] = acc.data['collection']
            acc.data = info
            if 'password' in info and not info['password'].startswith('sha1'):
                acc.set_password(info['password'])
            acc.save()
            resp = make_response( json.dumps(acc.data, sort_keys=True, indent=4) )
            resp.mimetype = "application/json"
            return resp
        else:
            if util.request_wants_json():
                if not auth.user.update(self.current_user,acc):
                    abort(401)
                resp = make_response( json.dumps(acc.data, sort_keys=True, indent=4) )
                resp.mimetype = "application/json"
                return resp
            else:
                admin = True if auth.user.update(self.current_user,acc) else False
                recordcount = portality.dao.Record.query({"terms":{'owner':acc.id}})['hits']['total']
                return render_template('account/view.html', 
                    current_user=self.current_user, 
                    search_options=json.dumps(self.search_options), 
                    record=json.dumps(acc.data), 
                    recordcount=recordcount,
                    admin=admin,
                    account=acc,
                    superuser=auth.user.is_super(self.current_user)
                )
github AlexIoannides / kubernetes-ml-ops / py-flask-ml-score-api / api.py View on Github external
"""Score data using an imaginary machine learning model.

    This API endpoint expects a JSON payload with a field called `X`
    containing an iterable sequence of features to send to the model.
    This data is parsed into Python dict and made available via
    `request.json`

    If `X` cannot be found in the parsed JSON data, then an exception
    will be raised. Otherwise, it will return a JSON payload with the
    `score` field containing the model's prediction.
    """

    try:
        features = request.json['X']
        prediction = model_predict(features)
        return make_response(jsonify({'score': prediction}))
    except KeyError:
        raise RuntimeError('"X" cannot be be found in JSON payload.')
github radiasoft / sirepo / sirepo / uri_router.py View on Github external
"""
    p = None
    s = None
    try:
        # must be first so exceptions have access to sim_type
        if kwargs:
            # Any (GET) uri will have simulation_type in uri if it is application
            # specific.
            s = sirepo.http_request.set_sim_type(kwargs.get('simulation_type'))
        f = func_or_name if callable(func_or_name) \
            else _api_to_route[func_or_name].func
        sirepo.api_auth.check_api_call(f)
        try:
            if data:
                p = sirepo.http_request.set_post(data)
            r = flask.make_response(f(**kwargs) if kwargs else f())
        finally:
            if data:
                sirepo.http_request.set_post(p)
    except Exception as e:
        if isinstance(e, (sirepo.util.Reply, werkzeug.exceptions.HTTPException)):
            pkdc('api={} exception={} stack={}', func_or_name, e, pkdexc())
        else:
            pkdlog('api={} exception={} stack={}', func_or_name, e, pkdexc())
        r = sirepo.http_reply.gen_exception(e)
    finally:
        # http_request tries to keep a valid sim_type so
        # this is ok to call (even if s is None)
        sirepo.http_request.set_sim_type(s)
    sirepo.cookie.save_to_cookie(r)
    return r