本文整理汇总了Python中flask.json.jsonify方法的典型用法代码示例。如果您正苦于以下问题:Python json.jsonify方法的具体用法?Python json.jsonify怎么用?Python json.jsonify使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.json
的用法示例。
在下文中一共展示了json.jsonify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: callback
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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)
示例2: home_post
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例3: home_post
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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]
示例4: uploadAudio
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例5: api_private_runs_by_month
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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)
示例6: default
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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()
示例7: delete_executor
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
#######
示例8: api_boot
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例9: api_get_projects
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例10: api_demo_data_project
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例11: api_init_model_ready
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例12: api_get_progress_info
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例13: api_classify_instance
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例14: api_delete_project
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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
示例15: get_ui_components
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import jsonify [as 别名]
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)