Python flask.json.jsonify() Examples

The following are 30 code examples of flask.json.jsonify(). 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.json , or try the search function .
Example #1
Source File: executors_blueprint.py    From chaos-monkey-engine with Apache License 2.0 6 votes vote down vote up
def delete_executor(executor_id):
    """
    Delete an executor

    Example request::

        DEL /api/1/executors/6890192d8b6c40e5af16f13aa036c7dc
    """
    manager.remove_executor(executor_id)
    return json.jsonify({
        "msg": "Executor %s succesfully deleted" % executor_id
    })

########
# UTILS
####### 
Example #2
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_classify_instance(project_id, doc_id):  # noqa: F401
    """Retrieve classification result.

    This request handles the document identifier and the corresponding label.
    The result is stored in a temp location. If this storage exceeds a certain
    amount of values, then the model is triggered. The values of the location
    are passed to the model and the storaged is cleared. This model will run
    in the background.
    """
    # return the combination of document_id and label.
    doc_id = request.form['doc_id']
    label = request.form['label']

    label_instance(project_id, doc_id, label, retrain_model=True)

    response = jsonify({'success': True})
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response 
Example #3
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_get_progress_info(project_id):  # noqa: F401
    """Get progress info on the article"""

    project_file_path = get_project_file_path(project_id)

    # open the projects file
    with open(project_file_path, "r") as f_read:
        project_dict = json.load(f_read)

    statistics = get_statistics(project_id)

    response = jsonify({**project_dict, **statistics})
    response.headers.add('Access-Control-Allow-Origin', '*')

    # return a success response to the client.
    return response


# I think we don't need this one 
Example #4
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_delete_project(project_id):  # noqa: F401
    """Get info on the article"""

    # some checks to check if there is a project to delete
    if project_id == "" or project_id is None:
        response = jsonify(message="project-delete-failure")
        return response, 500

    logging.info(f"delete project {project_id}")

    project_path = get_project_path(project_id)

    if project_path.exists() and project_path.is_dir():
        shutil.rmtree(project_path)

        response = jsonify({'success': True})
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response

    response = jsonify(message="project-delete-failure")
    return response, 500 
Example #5
Source File: oauth.py    From td-ameritrade-python-api with MIT License 6 votes vote down vote up
def callback():
    """ Step 3: Retrieving an access token.

    The user has been redirected back from the provider to your registered
    callback URL. With this redirection comes an authorization code included
    in the redirect URL. We will use that to obtain an access token.
    """

    # Grab the Refresh and Access Token.
    token_dict = app.config['auth_client'].grab_access_token_and_refresh_token(url=request.url)
    
    # Store it in the Session.
    session['oauth_token'] = token_dict

    if app.config['call_close']:
        return redirect(url_for('shutdown'))

    return jsonify(token_dict) 
Example #6
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_init_model_ready(project_id):  # noqa: F401
    """Check if trained model is available
    """

    error_path = get_project_path(project_id) / "error.json"
    if error_path.exists():
        print("error on training")
        with open(error_path, "r") as f:
            error_message = json.load(f)
        return jsonify(error_message), 400

    if get_proba_path(project_id).exists():
        logging.info("Model trained - go to review screen")
        response = jsonify(
            {'status': 1}
        )
    else:
        response = jsonify(
            {'status': 0}
        )

    response.headers.add('Access-Control-Allow-Origin', '*')
    return response 
Example #7
Source File: api_server.py    From kytos with MIT License 6 votes vote down vote up
def get_ui_components(self, section_name):
        """Return all napps ui components from an specific section.

        The component name generated will have the following structure:
        {username}-{nappname}-{component-section}-{filename}`

        Args:
            section_name (str): Specific section name

        Returns:
            str: Json with a list of all components found.

        """
        section_name = '*' if section_name == "all" else section_name
        path = f"{self.napps_dir}/*/*/ui/{section_name}/*.kytos"
        components = []
        for name in glob(path):
            dirs_name = name.split('/')
            dirs_name.remove('ui')

            component_name = '-'.join(dirs_name[-4:]).replace('.kytos', '')
            url = f'ui/{"/".join(dirs_name[-4:])}'
            component = {'name': component_name, 'url': url}
            components.append(component)
        return jsonify(components) 
Example #8
Source File: __init__.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, o):
        """
        支持 DBModel 和日期时间. (注: ``UUID``, ``dataclasses`` 等未继承)

        e.g.::

            # {job_number: 114, mobile: "13880000009", last_login: "2019-09-10 09:04:59", status: 1}
            return jsonify(TBUser.query.get(114).hide_keys('realname', 'role_id'))

        :param o:
        :return:
        """
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        if isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        if hasattr(o, 'keys') and hasattr(o, '__getitem__'):
            return dict(o)
        raise APIServerError() 
Example #9
Source File: private.py    From api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def api_private_runs_by_month():
    # The query takes ~6s on local SSD @ AMS on 2018-04-04.
    # It was taking ~20s when it was fetching all the table from DB and doing grouping locally.
    # TODO: use-count-table
    # FIXME: support fastpath
    now = datetime.now()
    end_date = datetime(now.year, now.month, 1)
    start_date = end_date - relativedelta(months=24)
    rawsql = """SELECT
        date_trunc('month', report.test_start_time) AS test_start_month,
        count(*) AS count_1
        FROM report
        WHERE report.test_start_time >= :start_date
        AND report.test_start_time < :end_date
        GROUP BY test_start_month
    """
    params = dict(start_date=start_date, end_date=end_date)
    q = current_app.db_session.execute(rawsql, params)
    delta = relativedelta(months=+1, days=-1)
    result = [
        {"date": (bkt + delta).strftime("%Y-%m-%d"), "value": value}
        for bkt, value in sorted(q.fetchall())
    ]
    return jsonify(result) 
Example #10
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_demo_data_project():  # noqa: F401
    """Get info on the article"""

    subset = request.args.get('subset', None)

    if subset == "plugin":
        result_datasets = get_dataset_metadata(exclude="builtin")
    elif subset == "test":
        result_datasets = get_dataset_metadata(include="builtin")
    else:
        response = jsonify(message="demo-data-loading-failed")

        return response, 400

    payload = {"result": result_datasets}
    response = jsonify(payload)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response 
Example #11
Source File: server.py    From crnn-lid with GNU General Public License v3.0 6 votes vote down vote up
def uploadAudio():

    def is_allowed(filename):
        return len(filter(lambda ext: ext in filename, ["wav", "mp3", "ogg"])) > 0

    file = request.files.getlist("audio")[0]

    if file and is_allowed(file.filename):
        filename = secure_filename(file.filename)
        file_path = path.join(app.config["UPLOAD_FOLDER"], filename)
        file.save(file_path)

        # convert_to_mono_wav(file_path, True)

        response = jsonify(get_prediction(file_path))
    else:
        response = bad_request("Invalid file")

    return response 
Example #12
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_get_projects():  # noqa: F401
    """Get info on the article"""

    projects = list_asreview_project_paths()
    logging.debug(list_asreview_project_paths)

    project_info = []
    for proj in projects:

        try:
            with open(proj / "project.json", "r") as f:
                res = json.load(f)
                assert res["id"] is not None
                project_info.append(res)
        except Exception as err:
            logging.error(err)

    response = jsonify({
        "result": project_info
    })
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response 
Example #13
Source File: server.py    From iLID with MIT License 6 votes vote down vote up
def uploadAudio():

    def is_allowed(filename):
        return len(filter(lambda ext: ext in filename, ["wav", "mp3", "ogg"])) > 0

    file = request.files.getlist("audio")[0]

    if file and is_allowed(file.filename):
        filename = secure_filename(file.filename)
        file_path = path.join(app.config["UPLOAD_FOLDER"], filename)
        file.save(file_path)

        # convert_to_mono_wav(file_path, True)

        response = jsonify(get_prediction(file_path))
    else:
        response = bad_request("Invalid file")

    return response 
Example #14
Source File: api.py    From asreview with Apache License 2.0 6 votes vote down vote up
def api_boot():  # noqa: F401
    """Get the boot info"""

    if os.environ.get("FLASK_ENV", None) == "development":
        status = "development"
    else:
        status = "asreview"

        try:
            import asreviewcontrib.covid19  # noqa
            status = "asreview-covid19"
        except ImportError:
            logging.debug("covid19 plugin not found")

    response = jsonify({"status": status})
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response 
Example #15
Source File: api_v2.py    From fabric8-analytics-server with Apache License 2.0 6 votes vote down vote up
def stack_analyses_with_request_id(external_request_id):
    """Handle stack analyses report fetch api."""
    logger.debug("GET request_id: {}".format(external_request_id))

    # 1. Build response builder with id and RDB object.
    sa_response_builder = StackAnalysesResponseBuilder(external_request_id,
                                                       RdbAnalyses(external_request_id))

    # 2. If there was no exception raise, means request is ready to be served.
    try:
        return jsonify(sa_response_builder.get_response())
    except SARBRequestInvalidException as e:
        raise HTTPError(400, e.args[0]) from e
    except RDBInvalidRequestException as e:
        raise HTTPError(404, e.args[0]) from e
    except RDBServerException as e:
        raise HTTPError(500, e.args[0]) from e
    except SARBRequestInprogressException as e:
        # Avoid HTTPError to ignore sentry reporting for Inprogress request.
        return jsonify({'error': e.args[0]}), 202
    except SARBRequestTimeoutException as e:
        raise HTTPError(408, e.args[0]) from e 
Example #16
Source File: main.py    From hangouts-chat-samples with Apache License 2.0 6 votes vote down vote up
def home_post():
    """Respond to POST requests to this endpoint.

    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    event_data = request.get_json()

    resp = None

    # If the bot is removed from the space, it doesn't post a message
    # to the space. Instead, log a message showing that the bot was removed.
    if event_data['type'] == 'REMOVED_FROM_SPACE':
        logging.info('Bot removed from  %s', event_data['space']['name'])
        return json.jsonify({})

    resp = format_response(event_data)
    space_name = event_data['space']['name']
    send_async_response(resp, space_name)

    # Return empty jsom respomse simce message already sent via REST API
    return json.jsonify({})

# [START async-response] 
Example #17
Source File: main.py    From hangouts-chat-samples with Apache License 2.0 6 votes vote down vote up
def home_post():
    """Respond to POST requests to this endpoint.

    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    data = request.get_json()

    resp = None

    if data['type'] == 'REMOVED_FROM_SPACE':
        logging.info('Bot removed from a space')

    else:
        resp_dict = format_response(data)
        resp = json.jsonify(resp_dict)

    return resp 
Example #18
Source File: api_v2.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def stack_analyses():
    """Handle request to trigger a new stack analyses report.

    GET method would raise error to provide missing request id to the user.
    """
    if request.method == 'GET':
        raise HTTPError(400, error="Request id missing")

    sa_post_request = None
    try:
        # 1. Validate and build request object.
        sa_post_request = StackAnalysesPostRequest(**request.form, **request.files)

    except ValidationError as e:
        # 2. Check of invalid params and raise exception.
        error_message = 'Validation error(s) in the request.'
        for error in e.errors():
            error_message += ' {}.'.format(error['msg'])
        logger.exception(error_message)
        raise HTTPError(400, error=error_message) from e

    # 3. Initiate stack analyses object
    sa = StackAnalyses(sa_post_request)

    # 4. Post request
    try:
        return jsonify(sa.post_request())
    except SAInvalidInputException as e:
        raise HTTPError(400, e.args[0]) from e
    except BackboneServerException as e:
        raise HTTPError(500, e.args[0])
    except RDBSaveException as e:
        raise HTTPError(500, e.args[0]) 
Example #19
Source File: user_api.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def handle_user_exception(e):
    """Exception handler for handling user management errors."""
    return jsonify(message=e.message, status='500'), 500 
Example #20
Source File: api_v2.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def liveness():
    """Handle the /liveness REST API call."""
    return jsonify({}), 200 
Example #21
Source File: user_api.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def handle_authorization_error(e):
    """Exception handler for handling authorization errors."""
    return jsonify(message='Authentication failed', status=e.status_code), 401 
Example #22
Source File: custom.py    From Flask-MonitoringDashboard with MIT License 5 votes vote down vote up
def custom_graph(graph_id, start_date, end_date):
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    with session_scope() as db_session:
        return jsonify(get_graph_data(db_session, graph_id, start_date, end_date)) 
Example #23
Source File: BoardListCatalog.py    From maniwani with MIT License 5 votes vote down vote up
def get(self, board_id):
        return jsonify(self.retrieve(board_id)) 
Example #24
Source File: Firehose.py    From maniwani with MIT License 5 votes vote down vote up
def get(self):
        return jsonify(self._get_threads()) 
Example #25
Source File: ThreadPosts.py    From maniwani with MIT License 5 votes vote down vote up
def get(self, thread_id):
        session = db.session
        thread = session.query(Thread).filter(Thread.id == thread_id).one()
        thread.views += 1
        session.add(thread)
        session.commit()
        return jsonify(self.retrieve(thread_id)) 
Example #26
Source File: api.py    From asreview with Apache License 2.0 5 votes vote down vote up
def api_start(project_id):  # noqa: F401
    """Start training the model
    """

    # get the CLI arguments
    asr_kwargs = deepcopy(app.config['asr_kwargs'])

    # add the machine learning model to the kwargs
    # TODO@{Jonathan} validate model choice on server side
    ml_model = request.form.get("machine_learning_model", None)
    if ml_model:
        asr_kwargs["model"] = ml_model

    # write the kwargs to a file
    with open(get_kwargs_path(project_id), "w") as fp:
        json.dump(asr_kwargs, fp)

    # start training the model

    py_exe = _get_executable()
    run_command = [
        py_exe,
        "-m", "asreview",
        "web_run_model",
        project_id,
        "--label_method",
        "prior"
    ]
    subprocess.Popen(run_command)

    response = jsonify({'success': True})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response 
Example #27
Source File: api.py    From asreview with Apache License 2.0 5 votes vote down vote up
def api_get_prior(project_id):  # noqa: F401
    """Get all papers classified as prior documents
    """
    lock_fp = get_lock_path(project_id)
    with SQLiteLock(lock_fp, blocking=True, lock_name="active"):
        label_history = read_label_history(project_id)

    indices = [x[0] for x in label_history]

    records = read_data(project_id).record(indices)

    payload = {"result": []}
    for i, record in enumerate(records):

        payload["result"].append({
            "id": int(record.record_id),
            "title": record.title,
            "abstract": record.abstract,
            "authors": record.authors,
            "keywords": record.keywords,
            "included": int(label_history[i][1])
        })

    response = jsonify(payload)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response 
Example #28
Source File: api.py    From asreview with Apache License 2.0 5 votes vote down vote up
def api_label_item(project_id):  # noqa: F401
    """Label item

    This request handles the document identifier and the corresponding label.
    The result is stored in a temp location. If this storage exceeds a certain
    amount of values, then the model is triggered. The values of the location
    are passed to the model and the storaged is cleared. This model will run
    in the background.
    """
    # return the combination of document_id and label.
    doc_id = request.form.get('doc_id')
    label = request.form.get('label')
    is_prior = request.form.get('is_prior', default=False)

    retrain_model = False if is_prior == "1" else True

    # [TODO]project_id, paper_i, label, is_prior=None
    label_instance(
        project_id,
        doc_id,
        label,
        retrain_model=retrain_model
    )

    response = jsonify({'success': True})
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response 
Example #29
Source File: flask_study.py    From notes with Apache License 2.0 5 votes vote down vote up
def zhihu_hot_list(type):
    result = {}
    if type =="zhihu":
        hot_list = acquire_hot_list(url="https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true")
        result = parse_zhihu_hot_list(hot_list)
    return json.jsonify(result) 
Example #30
Source File: api.py    From asreview with Apache License 2.0 5 votes vote down vote up
def api_init_project():  # noqa: F401
    """Get info on the article"""

    logging.info("init project")

    project_name = request.form['project_name']
    project_description = request.form['project_description']
    project_authors = request.form['project_authors']

    project_id = re.sub('[^A-Za-z0-9]+', '-', project_name).lower()

    try:
        init_project(
            project_id,
            project_name=project_name,
            project_description=project_description,
            project_authors=project_authors
        )

        response = jsonify({
            "project_id": project_id,
            "project_name": project_name,
            "project_description": project_description,
            "project_authors": project_authors
        })

    except Exception as err:
        logging.error(err)
        response = jsonify(message="project-init-failure")

        return response, 500

    return response