本文整理汇总了Python中flask.json.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python json.dumps方法的具体用法?Python json.dumps怎么用?Python json.dumps使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.json
的用法示例。
在下文中一共展示了json.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def __init__(self, response, status=None, headers=None, **kwargs):
""" Init a JSON response
:param response: Response data
:type response: *
:param status: Status code
:type status: int|None
:param headers: Additional headers
:type headers: dict|None
"""
# Store response
self._response_data = self.preprocess_response_data(response)
# PrettyPrint?
try:
indent = 2 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr else None
except RuntimeError: # "RuntimeError: working outside of application context"
indent = None
# Init super
super(JsonResponse, self).__init__(
json.dumps(self._response_data, indent=indent),
headers=headers, status=status, mimetype='application/json',
direct_passthrough=True, **kwargs)
示例2: counter
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def counter():
rpc = app.config['scheduler_rpc']
if rpc is None:
return json.dumps({})
result = {}
try:
data = rpc.webui_update()
for type, counters in iteritems(data['counter']):
for project, counter in iteritems(counters):
result.setdefault(project, {})[type] = counter
for project, paused in iteritems(data['pause_status']):
result.setdefault(project, {})['paused'] = paused
except socket.error as e:
app.logger.warning('connect to scheduler rpc error: %r', e)
return json.dumps({}), 200, {'Content-Type': 'application/json'}
return json.dumps(result), 200, {'Content-Type': 'application/json'}
示例3: active_tasks
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def active_tasks():
rpc = app.config['scheduler_rpc']
taskdb = app.config['taskdb']
project = request.args.get('project', "")
limit = int(request.args.get('limit', 100))
try:
tasks = rpc.get_active_tasks(project, limit)
except socket.error as e:
app.logger.warning('connect to scheduler rpc error: %r', e)
return '{}', 502, {'Content-Type': 'application/json'}
result = []
for updatetime, task in tasks:
task['updatetime'] = updatetime
task['updatetime_text'] = utils.format_date(updatetime)
if 'status' in task:
task['status_text'] = taskdb.status_to_string(task['status'])
result.append(task)
return json.dumps(result), 200, {'Content-Type': 'application/json'}
示例4: api_only
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def api_only(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
accepted = set(request.accept_mimetypes.values())
explicit = not(not request.args.get("json", False))
if not (accepted & API_MIMETYPES) and not explicit:
return abort(415, "Unsupported Media Type")
resp = fn(*args, **kwargs)
if not isinstance(resp, ResponseBase):
data, code, headers = unpack(resp)
# we've found one, return json
if isinstance(data, MarshalResult):
data = data.data
resp = make_response(json.dumps(data,
indent=explicit and 4 or 0),
code)
if headers:
resp.headers.update(headers)
resp.headers["Content-Type"] = 'application/json'
return resp
return wrapped
示例5: register_graph
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def register_graph():
digraph = request.args.get('digraph')
dataset = request.args.get('dataset')
treatment_name = request.args.get('treatment')
outcome_name = request.args.get('outcome')
df = dataiku.Dataset(dataset).get_dataframe()
model = CausalModel(
data=df,
treatment=treatment_name,
outcome=outcome_name,
graph=digraph,
)
identified_estimand = model.identify_effect()
causal_estimate_reg = model.estimate_effect(identified_estimand,
method_name="backdoor.linear_regression",
test_significance=True)
d = {'results': str(causal_estimate_reg)}
return json.dumps(d)
示例6: _set_user_storage
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def _set_user_storage(self):
from flask_assistant.core import user
# If empty or unspecified,
# the existing persisted token will be unchanged.
user_storage = user.get("userStorage")
if user_storage is None:
return
if isinstance(user_storage, dict):
user_storage = json.dumps(user_storage)
if len(user_storage.encode("utf-8")) > 10000:
raise ValueError("UserStorage must not exceed 10k bytes")
self._response["payload"]["google"]["userStorage"] = user_storage
示例7: get
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def get(self, skill_family_name):
"""Process an HTTP GET request"""
self._authenticate()
self.family_settings = self.setting_repository.get_family_settings(
self.account.id,
skill_family_name
)
self._parse_selection_options()
response_data = self._build_response_data()
# The response object is manually built here to bypass the
# camel case conversion so settings are displayed correctly
return Response(
response=json.dumps(response_data),
status=HTTPStatus.OK,
content_type='application/json'
)
示例8: demo4
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def demo4():
json_dict = {
'name': 'zhangsan',
'age': 18
}
# 使用falsk.json包下的dumps方法把一个字典对象转换为json格式的字符串
json_str = json.dumps(json_dict)
# 使用laod方法把json格式的字符串转换为一个字典对象
# dict_obj = json.load('{ "name": "zhangsan","age": 18}')
# json.dunps返回的json字符串在浏览器中Content-type是text/html
# 但是使用jsonify来处理字典对象的话返回的也是str,但是浏览器的content-type就变成了application/json
return jsonify(json_dict)
# 直接使用redirect函数进行重定向
# 重定向的反向解析:使用重定向路由的视图函数名字url_for(XXX),并且携带参数
示例9: _generate_etag
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def _generate_etag(etag_data, etag_schema=None, extra_data=None):
"""Generate an ETag from data
etag_data: Data to use to compute ETag
etag_schema: Schema to dump data with before hashing
extra_data: Extra data to add before hashing
Typically, extra_data is used to add pagination metadata to the hash.
It is not dumped through the Schema.
"""
if etag_schema is None:
raw_data = etag_data
else:
if isinstance(etag_schema, type):
etag_schema = etag_schema()
raw_data = etag_schema.dump(etag_data)
if MARSHMALLOW_VERSION_MAJOR < 3:
raw_data = raw_data.data
if extra_data:
raw_data = (raw_data, extra_data)
# flask's json.dumps is needed here
# as vanilla json.dumps chokes on lazy_strings
data = json.dumps(raw_data, sort_keys=True)
return hashlib.sha1(bytes(data, 'utf-8')).hexdigest()
示例10: get_unit_test_portfolios
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def get_unit_test_portfolios():
'''
Returns the available user portfolio names in the Investment Portfolio service.
Uses type='user_portfolio' to specify.
'''
portfolio_names = []
res = investmentportfolio.Get_Portfolios_by_Selector('type','unit test portfolio')
try:
for portfolios in res['portfolios']:
portfolio_names.append(portfolios['name'])
#returns the portfolio names as list
print("Portfolio_names:" + str(portfolio_names))
return json.dumps(portfolio_names)
except:
return "No portfolios found."
#Deletes all unit test holdings and portfolios for cleanup
示例11: get_queues
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def get_queues():
def try_get_qsize(queue):
if queue is None:
return 'None'
try:
return queue.qsize()
except Exception as e:
return "%r" % e
result = {}
queues = app.config.get('queues', {})
for key in queues:
result[key] = try_get_qsize(queues[key])
return json.dumps(result), 200, {'Content-Type': 'application/json'}
示例12: runtask
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def runtask():
rpc = app.config['scheduler_rpc']
if rpc is None:
return json.dumps({})
projectdb = app.config['projectdb']
project = request.form['project']
project_info = projectdb.get(project, fields=('name', 'group'))
if not project_info:
return "no such project.", 404
if 'lock' in projectdb.split_group(project_info.get('group')) \
and not login.current_user.is_active():
return app.login_response
newtask = {
"project": project,
"taskid": "on_start",
"url": "data:,on_start",
"process": {
"callback": "on_start",
},
"schedule": {
"age": 0,
"priority": 9,
"force_update": True,
},
}
try:
ret = rpc.newtask(newtask)
except socket.error as e:
app.logger.warning('connect to scheduler rpc error: %r', e)
return json.dumps({"result": False}), 200, {'Content-Type': 'application/json'}
return json.dumps({"result": ret}), 200, {'Content-Type': 'application/json'}
示例13: get_script
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def get_script(project):
projectdb = app.config['projectdb']
if not projectdb.verify_project_name(project):
return 'project name is not allowed!', 400
info = projectdb.get(project, fields=['name', 'script'])
return json.dumps(utils.unicode_obj(info)), \
200, {'Content-Type': 'application/json'}
示例14: inject_messages
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def inject_messages():
return dict(MESSAGES=json.dumps(get_messages()))
示例15: fallbackRender
# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import dumps [as 别名]
def fallbackRender(template, key=None):
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
resp = fn(*args, **kwargs)
if isinstance(resp, ResponseBase):
return resp
data, code, headers = unpack(resp)
accepted = set(request.accept_mimetypes.values())
explicit = not (not request.args.get("json", False))
if len(accepted & API_MIMETYPES) or explicit:
# we've found one, return json
if isinstance(data, MarshalResult):
data = data.data
resp = make_response(json.dumps(data,
indent=explicit and 4 or 0),
code)
ct = 'application/json'
else:
resp = make_response(render_template(template,
key=key,
data=data),
code)
ct = "text/html"
if headers:
resp.headers.update(headers)
resp.headers["Content-Type"] = ct
return resp
return decorated_view
return wrapper