本文整理汇总了Python中json.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python json.dumps方法的具体用法?Python json.dumps怎么用?Python json.dumps使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类json
的用法示例。
在下文中一共展示了json.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_session
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def save_session(self, session_id=None):
"""
Save the current session to a json file
"""
try:
base_dir = self.props["base_dir"]
except:
base_dir = ""
if session_id is None:
session_id = self.user.ask("Enter session id: ")
session_id = str(session_id)
json_output = str(json.dumps(self.to_json()))
path = os.path.join(base_dir, "json/" + self.model_nm + session_id + ".json")
with open(path, "w+") as f:
f.write(json_output)
#self.print_env()
#self.user.tell("Session saved")
示例2: __init__
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def __init__(self, url, method='get', data=None, params=None,
headers=None, content_type='application/json', **kwargs):
self.url = url
self.method = method
self.params = params or {}
self.kwargs = kwargs
if not isinstance(headers, dict):
headers = {}
self.headers = CaseInsensitiveDict(headers)
if content_type:
self.headers['Content-Type'] = content_type
if data:
self.data = json.dumps(data)
else:
self.data = {}
示例3: test_object_PUT_at_id
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def test_object_PUT_at_id(self):
"""Create object in collection using PUT at specific ID."""
index = self.client.get("/{}".format(self.API_NAME))
assert index.status_code == 200
endpoints = json.loads(index.data.decode('utf-8'))
for endpoint in endpoints:
collection_name = "/".join(endpoints[endpoint].split(
"/{}/".format(self.API_NAME))[1:])
if collection_name in self.doc.collections:
collection = self.doc.collections[collection_name]["collection"]
class_ = self.doc.parsed_classes[collection.class_.title]["class"]
class_methods = [x.method for x in class_.supportedOperation]
dummy_object = gen_dummy_object(
collection.class_.title, self.doc)
if "PUT" in class_methods:
dummy_object = gen_dummy_object(
collection.class_.title, self.doc)
put_response = self.client.put('{}/{}'.format(
endpoints[endpoint], uuid.uuid4()), data=json.dumps(dummy_object))
assert put_response.status_code == 201
示例4: test_object_PUT_at_ids
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def test_object_PUT_at_ids(self):
index = self.client.get("/{}".format(self.API_NAME))
assert index.status_code == 200
endpoints = json.loads(index.data.decode('utf-8'))
for endpoint in endpoints:
collection_name = "/".join(endpoints[endpoint].split(
"/{}/".format(self.API_NAME))[1:])
if collection_name in self.doc.collections:
collection = self.doc.collections[collection_name]["collection"]
class_ = self.doc.parsed_classes[collection.class_.title]["class"]
class_methods = [x.method for x in class_.supportedOperation]
data_ = {"data": list()}
objects = list()
ids = ""
for index in range(3):
objects.append(gen_dummy_object(
collection.class_.title, self.doc))
ids = "{},".format(uuid.uuid4())
data_["data"] = objects
if "PUT" in class_methods:
put_response = self.client.put(
'{}/add/{}'.format(endpoints[endpoint], ids),
data=json.dumps(data_))
assert put_response.status_code == 201
示例5: test_endpointClass_POST
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def test_endpointClass_POST(self):
"""Check non collection Class POST."""
index = self.client.get("/{}".format(self.API_NAME))
assert index.status_code == 200
endpoints = json.loads(index.data.decode('utf-8'))
for endpoint in endpoints:
if endpoint not in ["@context", "@id", "@type"]:
class_name = "/".join(endpoints[endpoint].split(
"/{}/".format(self.API_NAME))[1:])
if class_name not in self.doc.collections:
class_ = self.doc.parsed_classes[class_name]["class"]
class_methods = [
x.method for x in class_.supportedOperation]
if "POST" in class_methods:
dummy_object = gen_dummy_object(class_.title, self.doc)
post_response = self.client.post(
endpoints[endpoint], data=json.dumps(dummy_object))
assert post_response.status_code == 200
示例6: test_required_props
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def test_required_props(self):
index = self.client.get("/{}".format(self.API_NAME))
assert index.status_code == 200
endpoints = json.loads(index.data.decode('utf-8'))
for endpoint in endpoints:
if endpoint not in ["@context", "@id", "@type"]:
class_name = "/".join(endpoints[endpoint].split(
"/{}/".format(self.API_NAME))[1:])
if class_name not in self.doc.collections:
class_ = self.doc.parsed_classes[class_name]["class"]
class_methods = [
x.method for x in class_.supportedOperation]
if "PUT" in class_methods:
dummy_object = gen_dummy_object(class_.title, self.doc)
required_prop = ""
for prop in class_.supportedProperty:
if prop.required:
required_prop = prop.title
break
if required_prop:
del dummy_object[required_prop]
put_response = self.client.put(
endpoints[endpoint], data=json.dumps(dummy_object))
assert put_response.status_code == 400
示例7: send_daily_alert
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def send_daily_alert():
date = dt.datetime.now().strftime('%Y-%m-%d')
msg = get_market_signal_by_date(date)
# send notification via wechat
wx_client = WeChatClient({
'APP_ID': conf.WECHAT_APP_ID,
'APP_SECRET': conf.WECHAT_APP_SECRET,
})
try:
response = wx_client.send_all_text_message(
json.dumps(msg, ensure_ascii=False))
logger.debug(response)
except Exception as e:
logger.error(e, exc_info=True)
示例8: on_get
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def on_get(self, req, resp):
"""Method handler for GET requests.
:param req: Falcon request object
:param resp: Falcon response object
"""
state = self.state_manager
try:
designs = list(state.designs.keys())
resp.body = json.dumps(designs)
resp.status = falcon.HTTP_200
except Exception as ex:
self.error(req.context, "Exception raised: %s" % str(ex))
self.return_error(
resp,
falcon.HTTP_500,
message="Error accessing design list",
retry=True)
示例9: on_get
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def on_get(self, req, resp, hostname):
try:
latest = req.params.get('latest', 'false').upper()
latest = True if latest == 'TRUE' else False
node_bd = self.state_manager.get_build_data(
node_name=hostname, latest=latest)
if not node_bd:
self.return_error(
resp,
falcon.HTTP_404,
message="No build data found",
retry=False)
else:
node_bd = [bd.to_dict() for bd in node_bd]
resp.status = falcon.HTTP_200
resp.body = json.dumps(node_bd)
resp.content_type = falcon.MEDIA_JSON
except Exception as ex:
self.error(req.context, "Unknown error: %s" % str(ex), exc_info=ex)
self.return_error(
resp, falcon.HTTP_500, message="Unknown error", retry=False)
示例10: on_post
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def on_post(self, req, resp):
try:
json_data = self.req_json(req)
node_filter = json_data.get('node_filter', None)
design_ref = json_data.get('design_ref', None)
if design_ref is None:
self.info(req.context,
'Missing required input value: design_ref')
self.return_error(
resp,
falcon.HTTP_400,
message='Missing input required value: design_ref',
retry=False)
return
_, site_design = self.orchestrator.get_effective_site(design_ref)
nodes = self.orchestrator.process_node_filter(
node_filter=node_filter, site_design=site_design)
resp_list = [n.name for n in nodes if nodes]
resp.body = json.dumps(resp_list)
resp.status = falcon.HTTP_200
except Exception as ex:
self.error(req.context, "Unknown error: %s" % str(ex), exc_info=ex)
self.return_error(
resp, falcon.HTTP_500, message="Unknown error", retry=False)
示例11: task_validate_design
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def task_validate_design(self, req, resp, json_data):
"""Create async task for validate design."""
action = json_data.get('action', None)
if action != 'validate_design':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_validate_design"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
示例12: task_verify_site
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def task_verify_site(self, req, resp, json_data):
"""Create async task for verify site."""
action = json_data.get('action', None)
if action != 'verify_site':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_verify_site"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
示例13: task_prepare_site
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def task_prepare_site(self, req, resp, json_data):
"""Create async task for prepare site."""
action = json_data.get('action', None)
if action != 'prepare_site':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_prepare_site"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
示例14: task_verify_nodes
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def task_verify_nodes(self, req, resp, json_data):
"""Create async task for verify node."""
action = json_data.get('action', None)
if action != 'verify_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_verify_nodes"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
示例15: task_prepare_nodes
# 需要导入模块: import json [as 别名]
# 或者: from json import dumps [as 别名]
def task_prepare_nodes(self, req, resp, json_data):
"""Create async task for prepare node."""
action = json_data.get('action', None)
if action != 'prepare_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_prepare_nodes"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)