How to use the flask.jsonify 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 codeforamerica / projectmonitor / projmon / __init__.py View on Github external
_, _, github_path, _, _, _ = urlparse(resp.url)

                    if github_path != path:
                        message = 'Error in {guid}: {path} has moved to {github_path}'
                        kwargs = dict(guid=project['guid'], **locals())
                        raise Exception(message.format(**kwargs))

            if resp.status_code != 200:
                message = 'Missing {guid}: no {travis url}'
                raise Exception(message.format(**project))
    except Exception as e:
        status = str(e)
    else:
        status = 'ok'

    return jsonify(dict(status=status,
                        updated=int(time()),
                        dependencies=['Travis', 'Github'],
                        resources={}))
github igemsoftware / SYSU-Software-2015 / server / routes / design_view.py View on Github external
"""
    l = [] 
    for c in ComponentPrototype.query.order_by(ComponentPrototype.name.asc()).all():
        if c.id == 1: continue
        l.append({'name': c.name,
                  'introduction': c.introduction,
                  'source': c.source,
                  'risk': c.risk,
                  'type': c.type,
                  'BBa': c.BBa,
                  'bacterium': c.bacterium,
                  'attr': c.attr
                  })
    return jsonify(parts=l)
github tomoima525 / pipi / pipi / app.py View on Github external
def get_image_urls_json():
    _db = get_db()
    cur = _db.cursor()
    cur.execute('select public_id from images order by id desc limit 30')
    images = cur.fetchall()
    l = ['https://res.cloudinary.com/tomomisawedding/image/upload/c_pad,b_black,h_300,w_300/%s.jpg' %
         i[0] for i in images]
    return jsonify(images=l)
github usnistgov / SpectrumBrowser / services / spectrumbrowser / flaskr.py View on Github external
    @testcase
    def getLastSensorAcquisitionTimeWorker(sensorId, sessionId):
        try:
            util.debugPrint("getLastSensorAcquisitionTimeWorker: sensorId " +
                            sensorId + " sessionId " + sessionId)
            if not Config.isConfigured():
                util.debugPrint("Please configure system")
                abort(500)
            if not authentication.checkSessionId(sessionId, USER):
                abort(403)
            timeStamp = msgutils.getLastSensorAcquisitionTimeStamp(sensorId)
            return jsonify({"aquisitionTimeStamp": timeStamp})
        except:
            print "Unexpected error:", sys.exc_info()[0]
            print sys.exc_info()
            util.logStackTrace(sys.exc_info())
            traceback.print_exc()
            raise
github coreemu / core / webapp / node_routes.py View on Github external
interfaces.append({
            "id": interface_id,
            "netid": net_id,
            "name": interface.name,
            "mac": str(interface.hwaddr),
            "mtu": interface.mtu,
            "flowid": interface.flow_id
        })

    services = [x.name for x in getattr(node, "services", [])]

    emane_model = None
    if nodeutils.is_node(node, NodeTypes.EMANE):
        emane_model = node.model.name

    return jsonify(
        name=node.name,
        type=nodeutils.get_node_type(node.__class__).value,
        services=services,
        emane=emane_model,
        model=node.type,
        interfaces=interfaces,
        linksurl="/sessions/%s/nodes/%s/links" % (session_id, node.objid)
    )
github francescou / docker-compose-ui / main.py View on Github external
def project_container(name, container_id):
    """
    get container details
    """
    project = get_project_with_name(name)
    container = get_container_from_id(project.client, container_id)
    return jsonify(
        id=container.id,
        short_id=container.short_id,
        human_readable_command=container.human_readable_command,
        name=container.name,
        name_without_project=container.name_without_project,
        number=container.number,
        ports=container.ports,
        ip=container.get('NetworkSettings.IPAddress'),
        labels=container.labels,
        log_config=container.log_config,
        image=container.image,
        environment=container.environment,
        started_at=container.get('State.StartedAt'),
        repo_tags=container.image_config['RepoTags']
        )
github eclogue / eclogue / eclogue / api / job.py View on Github external
}), 400

    payload = load_ansible_playbook(body)
    if payload.get('message') is not 'ok':
        return jsonify(payload), 400

    data = payload.get('data')
    options = data.get('options')
    is_check = body.get('check')
    private_key = data.get('private_key')
    wk = Workspace()
    book_name = data.get('book_name')
    roles = data.get('roles')
    with build_book_from_db(name=book_name, roles=roles) as bookspace:
        if not bookspace:
            return jsonify({
                'message': 'invalid book',
                'code': 104000
            }), 400

        entry = wk.get_book_entry(data.get('book_name'),  data.get('entry'))
        # entry = os.path.join(bookspace, data['entry'])
        dry_run = bool(is_check)
        options['check'] = dry_run
        if dry_run:
            with NamedTemporaryFile('w+t', delete=True) as fd:
                if private_key:
                    key_text = get_credential_content_by_id(private_key, 'private_key')
                    if not key_text:
                        return jsonify({
                            'message': 'invalid private_key',
                            'code': 104033,
github censusreporter / census-api / census_extractomatic / api.py View on Github external
@app.errorhandler(400)
@app.errorhandler(500)
@crossdomain(origin='*')
def jsonify_error_handler(error):
    if isinstance(error, ClientRequestValidationException):
        resp = jsonify(error=error.description, errors=error.errors)
        resp.status_code = error.code
    elif isinstance(error, HTTPException):
        resp = jsonify(error=error.description)
        resp.status_code = error.code
    else:
        resp = jsonify(error=error.message)
        resp.status_code = 500
    app.logger.exception("Handling exception %s, %s", error, error.message)
    return resp
github thawsystems / docker-ida / ida-base / ida-service / flask_service.py View on Github external
except pexpect.TIMEOUT:
        return jsonify(error='request to ida timed out'), 408
    finally:
        if file_name is not None:
            _remove_ida_created_files(file_name)
            logger.info('Removed ida leftover files')

    if exit_code == 0:
        logger.info('Command %s finished executing successfully', command)
    else:
        logger.warn("Command %s didn't finish correctly, IDA returned exit code %s", command, exit_code)

    if exit_code != 0:
        return jsonify(error='ida finish with status code %s' % exit_code), 500
    else:
        return jsonify(message='OK'), 200